There is a very similar question here but I do not understand the following:
Imagine that I have a class for 2D mathematical vectors and I want to define the setter functions:
/** Setters **/
Vector2D& setX(double xcoor) {x = xcoor; return *this;}
Vector2D& setY(double ycoor) {y = ycoor; return *this;}
Now, the "this" pointer contains the address of the instance for which the functions are called.
Vector2D VV(2,4);
VV.setX(1).setY(5);
In this case "this" has the address of the VV instance. So why not just return this but return *this?
Right.
Suppose
setX
would return the pointerthen your code would be wrong:
The "correct" would be
VV.setX(1)->setY(5);
. However, there is no reason to use a pointer. I know it can be difficult to understand for beginners, because in teaching pointers are overused. Most of the time you do not care about pointers or the memory adress of objects.You return
*this
, because thats all what is needed to enable chaining. The caller has aVV
object so what you return is a reference to that, not something else.