Tuesday 29 November 2011

Hidden parameter : this Pointer to member function

Implicit this pointer


Whenever we create a class
There are data members and member functions...
for eg:
class A
{
int x;
public:
void display();
}

A obj,obj1,obj2;

Now each obj,obj1 and obj2 vil have there own local copy of x.
But there vil be only 1 copy of Display() in memory not THREE copies.
So how does the Display() know which objects'x X to show....??

This is solved by the compiler by implicitly passing a "this" pointer to display function.
Read the next line carefully
"A this pointer is a pointer which points to the calling object."
so obj.display();
In this case it vil be of type A and it vil point to address of obj.
so this call obj.display() will internally become A_display(&obj).
So &obj gives display() function the address of the calling object i.e this pointe.So it knows which object to access.
And REMEMBER this pointer is passed implicitly by the compiler i.e without the knowledge of the programmer.
But now u knw...lol

No comments:

Post a Comment