In C++, the this
pointer is a pointer that holds the memory address of the current object. It is a hidden argument to all non-static member functions and is available within the body of those functions.
The this
pointer can be used to refer to the object itself, and can be used to access the members of the object. For example, you might use this->member
to access a member variable or this->method()
to call a member function on the current object.
Here is an example of how you might use the this
pointer in a member function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class MyClass { public: MyClass(int value) : value_(value) {} void SetValue(int value) { // Use the this pointer to access the value_ member variable this->value_ = value; } private: int value_; }; |
The this
pointer can be useful when you have a local variable with the same name as a member variable, because it allows you to disambiguate between the two variables. It can also be useful for passing the current object as an argument to a function, because you can pass this
as a pointer to the object.
Here is an example of how you might use the this
pointer in a member function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> class MyClass { public: MyClass(int value) : value_(value) {} void SetValue(int value) { // Use the this pointer to access the value_ member variable this->value_ = value; } int GetValue() const { // Use the this pointer to access the value_ member variable return this->value_; } private: int value_; }; int main() { MyClass obj(10); std::cout << "obj.GetValue() = " << obj.GetValue() << std::endl; obj.SetValue(20); std::cout << "obj.GetValue() = " << obj.GetValue() << std::endl; return 0; } |
This code will output the following:
1 2 3 4 |
obj.GetValue() = 10 obj.GetValue() = 20 |
In the SetValue
function, the this
pointer is used to access the value_
member variable and assign it the value of the value
parameter. In the GetValue
function, the this
pointer is used to access the value_
member variable and return its value.