The purpose of this c++ is used mainly when programming with classes. Each time a member function is called, it is automatically passed as a pointer called this, to the object on which it is called. In Simple English terms, it is a reference to the current object.

This c++ can’t be used in friend functions as friends are not members of the class. Only member functions can have this pointer.

#include<iostream>
using namespace std;

/* local variable is same as a member's name */
class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this−>x = x;
}
void print() { cout << "x = " << x << endl; }
};

int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
Share this post