Returning this pointer when the return type of a function is a reference (C++)

311 Views Asked by At

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?

1

There are 1 best solutions below

0
On

In this case "this" has the address of the VV instance.

Right.

So why not just return this but return *this?

Suppose setX would return the pointer

Vector2D* setX(double xcoor) {x = xcoor; return this;}
      //^--- no reference but pointer        ---^

then your code would be wrong:

Vector2D VV(2,4);
VV.setX(1).setY(5);
    //    ^ ---------  error object has no class type, you cannot use .

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 a VV object so what you return is a reference to that, not something else.