Note 18.9.1.
In some other programming languages, like javascript,
this is required and every access of a member variable needs to use this.
this means the object executing the member function. But at that point, we did not delve into what this actually is. Now that we have covered pointers, we are ready to do so. this is a pointer that is automatically initialized with the memory address of the current object.
this inside a member function like Point::getX() to get the address of the current object:
this is to explicitly access member variables or functions of the current object.
getX(). It currently has return m_x. The m_x in it is understood to mean βthe m_x of the current objectβ. Writing this->m_x explicitly says that is what we want to do:
double Point::getX() {
return this->m_x;
}
this-> within member functions to make accessing members explicit. (Though we are already using the m_ naming convention to clarify which variables are members.) However, keep in mind that this-> can only be used to access member variables or functions. You can not use it to access local variables or parameters that are not a part of the object. For example, in setX, you can use it on m_x, but not on the parameter x:
Point::setX(double x) {
this->m_x = x; // correct, explicit use of this-> to access member
m_x = x; // also correct, m_x is implicitly this->m_x
this->m_x = this->x; // incorrect, x is not a member of Point
}
this is required and every access of a member variable needs to use this.
this is to allow an object to return either its address or a reference to itself.
double* Point::getAddress() {
return this; // this is the memory address of the current object
}
Point& Point::getReference() {
return *this; // return "the thing that this points at"
}
*this to get the object itself. The & in the return type indicates that we are returning a reference to the object, not a copy of it.
p1.setX(3.0).setY(4.0). For example, we could rewrite setX and setY to return references:
Point& Point::setX(double x) {
m_x = x;
return *this;
}
Point& Point::setY(double y) {
m_y = y;
return *this;
}
setX does its work, it returns the object that was executing it. So p1.setX(3.0) turns into p1, which is then used to execute setY(4.0).
Point function isSelf that takes a pointer to a Point as its parameter and returns true if that memory address is its own address.