Role of this pointer

The role of ‘this’ keyword is to represent an object that invokes the member function. It points to the object from where ‘this’ function was called. It is automatically passed to a member function when it is called.
e.g. when we call A.func(), It will be set as the address of A.

‘this pointer’ is used as a pointer to the object of  class instance by the member function. The address of the class instance is passed as an implicit parameter to the member functions.

When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object, that is the object on which the function is invoked. This type o pointer is known as ‘this’ pointer. It is internally created at the time of function call.

The ‘this’ pointers are important when operators are overloaded.

For Example: Consider a class with int and float data members and overloaded Pre-increment operator ++ :

class MyClass
int i;
float f;
MyClass ()
i = 0;
f = 0.0;
MyClass (int x, float y)
i = x; f = y;
MyClass operator ++()
i = i + 1;
f = f + 1.0;
return *this; //this pointer which points to the caller object
MyClass show()
cout<<”The elements are:\n” cout<i<<”\n<f; //accessing
data members using this

int main()
MyClass a;
++a; //The overloaded operator function ++()will return a’s this
retun 0;


The Output will be:

The elements are:

More in sem3
C++ references variable

C++ references variable A c++ reference variable is another name for an already existing variable. Once a reference is initialized...