In C++, this
is an implicit pointer that refers to the current object of a class. It is automatically available inside every non-static member function of a class and can be used to access the members of the current object.
this
is useful when you need to refer to the current object inside a member function, especially when the function takes parameters with the same name as the class members. In such cases, using this
can help avoid naming conflicts and make the code clearer. Additionally, this
can be used to return a reference to the current object, allowing for method chaining.
Note that this
is a pointer, not an object, so you must use the arrow operator (->
) to access the members of the current object.
Here's an example of using this
inside a member function:
class MyClass { public: void printAddress() { cout << "Object address: " << this << endl; } }; int main() { MyClass obj; obj.printAddress(); return 0; }
Here's an example of using this
inside a class:
class MyClass { private: int x; public: MyClass(int x) { this->x = x; } void printX() { cout << "x = " << this->x << endl; } }; int main() { MyClass obj(42); obj.printX(); return 0; }
In this example, we have defined a class MyClass
with a private member x
. The constructor of the class takes an integer argument and assigns it to the x
member using this->x
. The printX
member function then prints the value of x
using this->x
.
When we create an object of the MyClass
class and call printX
on it, we see the value of x
printed to the console.
Using this
inside a class is useful when you need to refer to the current object to access its members or to resolve naming conflicts. It can also be used to return a reference to the current object, allowing for method chaining.
Note that this
is a pointer, so you must use the arrow operator (->
) to access the members of the current object.