C++ The this Pointer
The this Pointer
In the Constructors chapter, the parameters had short names, like x, y and z. It would be clearer to give them the same names as the attributes, like brand and year.
But then brand = brand; is confusing. Which brand is the attribute, and which is the parameter?
The this pointer solves this. Inside a class, this points to the current object, so this->brand always means the attribute:
Example
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;
}
this->brand is the attribute of the object, and brand is the parameter.
The -> Operator
Because this is a pointer, you cannot use a dot to reach the attributes. Instead, you use the arrow operator ->, which is written with a minus sign and a greater than sign.
The arrow is a short way to dereference a pointer and use a dot at the same time. These two lines do the same:
this->brand = brand;
(*this).brand = brand;
Use -> every time you access a member through a pointer. It is shorter, and easier to read.
Note: Without this->, brand = brand; only gives the parameter its own value, and the attribute is not changed.
Use this in Methods
this works in all methods of a class, not only in constructors:
Example
class Player {
public:
string name;
int score = 0;
void addScore(int score) {
this->score += score;
}
};
int main() {
Player p1;
p1.name = "Liam";
p1.addScore(10);
p1.addScore(5);
cout << p1.name << " has " << p1.score << " points";
return 0;
}
When the names are different, you do not need this. But many programmers use it anyway, because it shows clearly that the code changes an attribute of the object.