C++ this pointer

tutorial and example
tutorial and example

‘this’ is a pointer that points to object for which this function was called. The ‘this’ pointer holds the memory address of current object. The ‘this’ pointer is implicitly passed to a member function when it is called.

Consider the following simple example:

The variable ‘id’ can be used directly inside a member function, as

The above initialization statement can be written using ‘this’ pointer, as

C++ internally use the initialization of id=10; as this->id=10;

Another key feature of the ‘this’ pointer is to return the object on which it is pointing. For example

The above statement inside member function returns the object which is invoking the member function.

C++ ‘this’ Example 1

Output:

C++ ‘return *this’ Example 2

Output: