the output of the following program is 10 0 whereas according to me the output should be 10 20 because obj.setX(10) returns a pointer to the current object ,that is, obj so the setY(20) would be executed as this->setY(20) so the value of y should be 20 but it isnt,please smbody help me if i am wrong
#include<iostream>
usingnamespace std;
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;
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
When evaluating the above:
First get obj1
then call setX(10) on it. This sets obj1 x to 10 and returns a copy
So now you have copyOfobj1.setY(20) left to evaluate, This sets copyOfobj1 y to 20.