How to use the ‘this’ pointer in C++?
In C++, the ‘this’ pointer is used to point to the current object. It serves as an implicit parameter that points to the object instance calling the member function. The ‘this’ pointer can be used within a member function to access the current object’s member variables and member functions.
The method of using this pointer is as follows:
- Accessing member variables using the this pointer within a member function.
class MyClass {
public:
int x;
void setX(int value) {
this->x = value;
}
};
In the above code, the this pointer is used to reference the x variable of the current object instance.
- Call other member functions using the this pointer within a member function.
class MyClass {
public:
void func1() {
// do something
}
void func2() {
this->func1();
}
};
In the above code, the func1 function was called using the this pointer.
It is important to note that the “this” pointer can only be used within member functions and cannot be used in static member functions or global functions. Additionally, the “this” pointer is a constant pointer and its value cannot be modified.