In the following class definition:
#include<iostream>
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
I don't understand why we should put an *
in front of this
in the setX
or setY
functions. I know this
is a pointer to the current object and the *
returns the pointed object, but since there is a &
in the functions' return values, which means that the function returns a reference to a Test
object. Then, shouldn't the return variable also be a reference (that is a pointer), like this:
Test &setX(int a) { x = a; return this; }
?
As an alternative, I believe
Test setX(int a) { x = a; return *this; }
would also be correct because the return value is not a pointer, but the pointed object, which of type Test
(and not of type pointer to Test
: Test&
).
Why, if it's the case, are they not correct?