Quick explanation of the This keyword in C++

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

The this keyword can’t be used in friend functions as friends are not members of the class. Only member functions can have a this pointer.

using namespace std;
/* local variable is same as a member's name */
class Test
 int x;
 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;
 return 0;
Share this post