Inside a member function, this is a pointer to the object the member function was invoked on and cannot be reassigned:
class Circle {
public:
double area() { return 3.14 * this->radius * this->radius; }
double radius;
};
Circle c;
c.radius = 2.0;
c.area(); // this == &cFields can be accessed without this since the compiler adds it implicitly. this->radius and radius are equivalent:
double area() { return 3.14 * radius * radius; }this is needed to differentiate a parameter and field with the same name:
class Circle {
public:
void setRadius(double radius) {
this->radius = radius;
}
double radius;
};this can be dereferenced to get a reference to the object itself. Returning *this lets member function calls be chained:
class Circle {
public:
Circle& setRadius(double r) {
radius = r;
return *this;
}
Circle& scale(double factor) {
radius *= factor;
return *this;
}
double radius;
};
Circle c;
c.setRadius(2.0).scale(3.0); // radius = 6Note
this cannot be used in static member functions.
Dan