2

When returning a reference to the object on which the function is invoked, the returned reference can be used to chain function calls on a single object.

Here, I am applying the same concept. But I am getting different output if I initialize objects differently.

First example:

#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(5, 5);

  // Chained function calls.  All calls modify the same object
  // as the same object is returned by reference
  obj1.setX(10).setY(20);

  obj1.print();
  return 0;
}

Output is 10 and 20, which is correct.

However, output is not correct for the second example:

#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;
}

Output is 10 and 0.

Why? I think both are the same, the output of the second program should be 10 and 20 too. What is the reason it's different?

1
  • 4
    You tagged this C# but your code appears to be C++, which is it? Commented Nov 28, 2013 at 20:00

1 Answer 1

5

The difference is that the second version of your program returns by value. This means that the second call (i.e. setY) is performed on a copy of obj1, not on the obj1 itself. That's why only X ends up being set, but not Y.

In your first program, on the other hand, the setters return their results as a reference. This means that no copy is being made, so setY is called on the same object as setX, not on its copy.

Sign up to request clarification or add additional context in comments.

2 Comments

then Why its setting x only why not y also
@vivekjain Because the initial call (i.e. setX) is done on the object itself, before the setter gets to make a copy (implicitly, through returning by value).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.