C++ this Keyword
Example
Use this to access the attributes of the current object:
class Car {
public:
string brand;
int year;
Car(string brand, int year) {
this->brand = brand;
this->year = year;
}
};
int main() {
Car myCar("Ford", 1969);
cout << myCar.brand << " " << myCar.year;
return 0;
}
Definition and Usage
The this keyword is a pointer to the current object. It is available inside class methods and constructors.
Use it when a parameter has the same name as an attribute. In the example above, this->brand is the attribute of the object, and brand is the parameter.
Because this is a pointer, you use the arrow operator -> instead of a dot to access the attributes.
Related Pages
Read more about the this pointer in our C++ The this Pointer Tutorial.