this pointer addresses the class object for which the member function is called.const member function is a pointer to the class type, a pointer to a const class type in a const member function, and a pointer to a volatile class type in a volatile member function.inline void move( Screen* this, int r, int c )
{
this->_cursor = ...;
}
myScreen.move( 2, 2 )
//is translated into
move( &myScreen, 2, 2 )
this pointerclass MyClass {
int value;
public:
void setValue(int value) {
this->value = value; // "this->value" is the member; "value" is the parameter.
}
};
class MyClass {
int x, y;
public:
MyClass& setX(int x) {
this->x = x;
return *this; // Enables chaining.
}
MyClass& setY(int y) {
this->y = y;
return *this; // Enables chaining.
}
};
// Usage:
MyClass obj;
obj.setX(10).setY(20);
class MyClass {
int data;
public:
MyClass& operator=(const MyClass& other) {
if (this == &other) // Check for self-assignment.
return *this;
// Copy data...
data = other.data;
return *this;
}
};
Sometimes you need to pass the current object’s address to other functions or methods. You can do this directly using this.
In C++11 and later, when using lambdas inside member functions, you might capture this to access members of the current object:
class MyClass {
int value;
public:
void doSomething() {
auto lambda = [this]() {
// Use this->value inside the lambda.
return this->value;
};
int result = lambda();
}
};