Search code examples
c++pointersthispass-by-reference

Returning a reference to the calling object (C++)


Having a bit of a hard time understanding this code:

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

Why would we have to return "*this" as a reference instead of just returning "*this"?


Solution

  • If setX were changed to

    Test setX(int a) { x = a; return *this; }
    

    then it returns a copy of *this instead of a reference to it. So in

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

    the setY is called on the copy, and not on obj1 itself. The copy is discarded and obj1.y is never modified from its initial value of 5.