Introduction
- The 'this' pointer is a constant pointer that holds the memory address of the current object and internally created at the time of function call.
- It is important when operators are overloaded.
- The 'this' pointer is automatically passed to a member function when it is called.
- It is used to represent an object that invokes the member function.
- It is not available in static member functions as static member functions can be called without any object.
- Friend function do not get 'this' pointer, because friends are not members of a class.
- Only member functions have a 'this' pointer.
The 'this' pointer is used in two situations:
1. When local variable's name is same as member's name.
2. When a reference to a local object is returned.
Example : Demonstrating the working of 'this' pointer
1. When local variable's name is same as member's name.
#include<iostream>
using namespace std;
class TestThisPointer // Local variable is same as a member's name
{
private:
int a;
public:
void getvalue(int a)
{
this->a = a; // The 'this' pointer is used to retrieve the object's x hidden by the local variable 'x'
}
void showvalue()
{
cout << "Value of A = " << a << endl;
}
};
int main()
{
TestThisPointer tp;
int a = 10;
tp.getvalue(a);
tp.showvalue();
return 0;
}
Output:
Value of A = 10
2. When a reference to a local object is returned.
#include<iostream>
using namespace std;
class TestThisPointer
{
private:
int a;
int b;
public:
TestThisPointer(int a = 0, int b = 0) //Parameterized Constructor
{
this->a = a;
this->b = b;
}
TestThisPointer &getvalue(int x)
{
a = x;
return *this;
}
TestThisPointer &getval(int y)
{
b = y;
return *this;
}
void showvalue()
{
cout<<"Value of x = "<<a<<endl;
cout<<"Value of y = "<<b<< endl;
}
};
int main()
{
TestThisPointer tp(5,5); //Chained function calls. All calls modify the same object as the same object is returned by reference
tp.getvalue(10).getval(20);
tp.showvalue();
return 0;
}
Output:
Value of x = 10
Value of y = 20
In the above example, when a reference to a local object is returned, the returned reference can be used to chain function calls on a single object.


