I have this code:
class Something
{
private:
int m_value = 0;
public:
Something add(int value)
{
m_value = value;
return *this;
}
int getValue()
{
return m_value;
}
};
int main()
{
Something a;
Something b = a.add(5).add(5);
cout << a.getValue() << endl;
cout << b.getValue() << endl;
}
output:
5
10
I tried to make method add() to return *this and execute after that like (*this).add(5), but this doesn't work. However, b is good (how?). I expected a to be 10 also as b.
So, where did I miss the usage of hidden pointer? What should i do to use a.add(5).add(5) as it supposed to have the m_value of a to be 10?
CodePudding user response:
add() is returning *this by value, so it is returning a copy of *this, so the chained add() is modifying the copy, not the original.
add() needs to return *this by reference instead:
Something& add(int value)
{
m_value = value;
return *this;
}
UPDATE: a initially has m_value set to 0, then a.add(5) sets a.m_value to 5 and then returns a copy of a. Then <copy>.add(5) sets <copy>.m_value to 10 and returns another copy, which is then assigned to b. That is why you see a is 5 but b is 10.
