rad123
rad123

Reputation: 187

Chaining function using 'this' pointer

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

In this program, if I use the chaining functions, values of x and y it comes to be : x=10, y=0 instead of x=10 , y=20

If instead of chaining function, I use: obj1.setX(10) and obj1.setY(20) separately, x value comes to be 10 y value comes to 20. Can someone please explain why it is like this.

Upvotes: 0

Views: 727

Answers (2)

LibertyPaul
LibertyPaul

Reputation: 1167

You can either return a reference on an object:

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

Or to store copy of changed object:

Test obj1;
Test objCopy = obj1.setX(10).setY(20);
objCopy.print();

First is more efficient due to not copying object.

Upvotes: 1

Douglas Leeder
Douglas Leeder

Reputation: 53310

Your set* methods are returning copies of the Test object.

So when you chain your calls, the setY is applied to the temporary copy, and thrown away.

Upvotes: 1

Related Questions