Q:

Why Output of c++ code changes when I change the function return type?

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; }
};

int main()
{
  Test obj1(5, 5);
  obj1.setX(10).setY(20);
  obj1.print();
  return 0;
}

The above code has output as 10 20 but when I change the return type of 
Test &setX to Test setX and Test &setY to Test setY, the output changes to 10 5. Can anyone explain the reason for the same ? This is not an assignment quoestion or anything related to homework.

A:

It is all about temporary object. 
In the version without return reference, i.e. return type is Test
Your code is equivalent to 
Test obj1(5, 5);
Test temp1 = obj1.setX(10);
Test temp2 = temp1.setY(20);
// temp2 will have x = 10 and y = 20, but the object is discarded
obj1.print();

as you can see setY(20) is called on an temporary object, and the returned value is discarded. So only the first setX(10) actually modify obj1
On the other hand, if you return a reference, i.e. the return type is Test &, no temporary will be created. So both setX(10) and setY(20) will affect the original object (obj1), because the method are called on a same object.

A:

In the following line when you return a value (and not a reference) you end up having the obj1.setX(10) returning a new object. On this new object (that will be discarded) setY is called but the original remains unchanged
obj1.setX(10).setY(20);

