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 10 20
when change return type of test &setx
test setx
, test &sety
test sety
, output changes 10 5
. can explain reason same ? not assignment quoestion or related homework.
it temporary object.
in version without return reference, i.e. return type test
code equivalent
test obj1(5, 5); test temp1 = obj1.setx(10); test temp2 = temp1.sety(20); // temp2 have x = 10 , y = 20, object discarded obj1.print();
as can see sety(20)
called on temporary object, , returned value discarded. first setx(10)
modify obj1
on other hand, if return reference, i.e. return type test &
, no temporary created. both setx(10)
, sety(20)
affect original object (obj1
), because method called on same object.
Comments
Post a Comment