The this
pointer in C++ points to the object that invokes the member function. This keyword is only accessible within the nonstatic member functions of a class/struct/union type.
There are many ways to use the this
pointer.
When the parameter name is the same as the private variable’s name, we use the this
keyword inside the method to distinguish between the two when assigning values.
class ClassName
{
private:
int sameName;
public:
ClassName functionName(int sameName)
{
this->sameName = sameName;
//the variable used with "this", is the class variable
}
We can also use this
to return the reference to the calling object.
ClassName& functionName()
{
//code
return *this; //returns the reference to the object
}
this
in constructorsA this
pointer is always passed to the constructor. It holds the object’s address that is being constructed during that call.
class Age{private:int a;public:Age(int a = 0){cout << "Address of object = " << this << endl;this->a = a;}Age& setAge(int x){cout << "Address of object = " << this << endl;a = x;return *this; //returns the current object}void getAge(){cout << "Address of object = " << this << endl;cout << "The age is " << a << endl;}};int main() {Age obj;//we don't need to explicitly call getAge() now, we can call it on the returned object.obj.setAge(20).getAge(); //(function chaining)return 0;}
Free Resources