this pointer

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
using namespace 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;
}
Last edited on
setX and setY return copies instead of references.
11
12
  Test &setX(int a) { x = a; return *this; }
  Test &setY(int b) { y = b; return *this; }
okay then y is the value of x updated to 10 if i dont return by reference
closed account (z05DSL3A)
obj1.setX(10).setY(20);


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.
Topic archived. No new replies allowed.