What is this pointer ?

this pointer is pointer that is accessible only inside the member functions of a class and points to the object who has called this member function.
Let’s understand by an example,

Rise of this pointer : Behind the scene

Let’s understand this pointer in a step by step example,

Create a class Sample that contains a member variable m_value and one function display() that prints the value of m_value.

Now Let’s create an object of this class display() member function

Inside this display function are printing m_value. But what happens behind the scenes ??

Whenever a member function is called through an object, compiler secretly pass the pointer of calling object to this member function i.e.

Compiler will secretly convert statement,

to,

Also, inside every member function compiler secretly pass the first parameter as the address of calling object i.e.

will be converted secretly to,

So, this is how this pointer comes in to picture. this pointer is secretly passed to each member function by the compiler. Also, when we access any member variable in member function, compiler uses this secretly passed this pointer to access that member variable.

 

So, display() function will be secretly changed by the compiler behind the scenes as follows,

Therefore, this pointer is accessible only inside member functions and points the address of the object with whom this member function is called.

Complete Executable code is as follows,

 

Click Here to Subscribe for more Articles / Tutorials like this.