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