简体   繁体   中英

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.

It is all about temporary object.

In the version without return reference, ie 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, ie 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.

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

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

If you define

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

result always will be 10 and 20.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM