In C++, the ‘this’ keyword is a constant pointer to object. It is actually a local variable defined in each member function, including constructors and destructors, which get initialized with object’s address passed by the caller.
Whenever, a public method called using a object, object’s address is passed to the member function and then the member function copies this supplied address to ‘this’ variable. Since ‘this’ variable is created on stack, each member method call will have separate ‘this’ variable on stack. Now using ‘this’ pointer, each of the data member is accessed in the method.
There can be two ways to pass object's address to the member function. 1) By pushing address on stack 2) by copied address in a register. Compiler can use any of the above method or can use any other method too.
Let’s take an example:
class test {
private:
int data;
public:
int public_data;
test() { data = public_data = 0; }
void display()
{ printf("\ndata = %d, public_data = %d", data, public_data); }
};
Let’s see the dis-assembly code generated for public method call on object:
test obj;
// Object’s address is getting copied in ECX register to supply it
// as input to constructor.
lea ecx,[obj]
call test::test (411195h) // constructor is getting called
obj.display();
// Object’s address is getting copied in ECX register to supply it
// as input to display method
lea ecx,[obj]
call test::display (411235h)
Now let's see the dis-assembly code of display method:
void display()
{
........
// Here ECX register contain object's address. Its value is getting copied to
// 'this' variable
mov dword ptr [ebp-8],ecx
printf("\ndata = %d, public_data = %d", data, public_data);
mov esi,esp
mov eax,dword ptr [this] // getting object's address
mov ecx,dword ptr [eax+8] //accessing 'public_data' value using 'this' pointer
push ecx
mov edx,dword ptr [this]
mov eax,dword ptr [edx+4] //accessing 'data' value using 'this' pointer
push eax
push offset string "\ndata = %d, public_data = %d" (415B10h)
call dword ptr [__imp__printf (4192D4h)]
......
}
In above dis-assembly code, we can see that the 'this' pointer is getting initialized with the object's address supplied by the caller. And the data members are getting accessed via 'this' pointer.