bornfree
bornfree

Reputation: 2528

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.

Upvotes: 0

Views: 192

Answers (4)

marom
marom

Reputation: 5230

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

Upvotes: 4

finesse
finesse

Reputation: 117

when you change Test &setX(int a) into Test setX(int a), the function Test setX(int a) returns a new object. obj1.setX(10).setY(20) equal to the follows:

  Test newobj = obj1.setX(10);
  newobj.setY(20);

  obj1.print();      // 10, 5
  newobj.print();    // 10, 20

Upvotes: 1

goGud
goGud

Reputation: 4333

If you define

obj1.setX(10);
obj1.setY(20);

result always will be 10 and 20.

Upvotes: 0

Bryan Chen
Bryan Chen

Reputation: 46578

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.

Upvotes: 6

Related Questions