• Now Online : 35
  • admin@codemyne.net


If every instance of a class carries a copy of the member functions within it, it would be a considerable overhead on system memory, especially if the functions happen to be lengthy. As an alternative, each object holds its own copy of the data members alone, and a pointer to a list of methods of the class. Only one copy of the member functions exists in memory.

But in such a case, when a function call is made, how does the compiler know which object is making the function call? For example, when two objects of the word class exist, word1 and word2, each with its own copy of member data, suppose the function getword were to be invoked, how does it know which copy of str_word is to be returned,

word1.str_word or word2.str_word?

The answer to this is the ‘this’ pointer. Each method of a class contains a pointer of its class type, named ‘this’. The ‘this’ pointer contains the address of the object through which the function is being invoked. This pointer is automatically generated by the compiler when an object is created. The programmer can also reference the ‘this’ pointer explicitly. The following example illustrates the usage of the ‘this’ pointer:

    char *word::getword()
        return this->str_word;

there are circumstances, however, when the user will have to reference the ‘this’ pointer

    word::word(char *str_word)
    /* the variable and member data have the same name, invoking confusion */
        this->str_word=new char [strlen(str_word)];
        strcpy (this->str_word, str_word);

In the above example, without the ‘this’ pointer, confusion would arise as to which str_word is being referenced, the member data or the variable that was passed as a parameter.

Comments/Suggestions are invited. Happy coding......!

Comments Post a Comment