There are a lot of places where we should use this pointer. Below I am mentioning some scenarios where you should use this pointer, so let see.
1. When the local variable’s name is the same as the member’s name?
#include<iostream>
using namespace std;
class Test
{
private:
//member variable
int x;
public:
void setX (int x) //x is local
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void DisplayX()
{
cout << "x = " << x << endl;
}
};
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.DisplayX();
return 0;
}
2. To return a reference to the calling object.
/* Reference to the calling object can be returned */
Test& Test::func ()
{
// Some processing
return *this;
}
3. When needs chain function calls on a single object.
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0)
{
this->x = x;
this->y = y;
}
Test &setX(int a)
{
x = a;
return *this;
}
Test &setY(int b)
{
y = b;
return *this;
}
void print()
{
cout << "x = " << x << " y = " << y << endl;
}
};
int main()
{
Test obj(7, 7);
obj.print();
// Chained function calls. All calls modify the same object
// as the same object is returned by reference
obj.setX(10).setY(20).print();
return 0;
}
Answer:
There are a lot of places where we should use this pointer. Below I am mentioning some scenarios where you should use this pointer, so let see.
1. When the local variable’s name is the same as the member’s name?
2. To return a reference to the calling object.
3. When needs chain function calls on a single object.
Output:
x = 7 y = 7
need an explanation for this answer? contact us directly to get an explanation for this answerx = 10 y = 20