Reputation: 37
While overloading += operator why do we have to return by reference. for e.g. the below code also do the same thing
class Integer
{
int i;
public:
Integer::Integer(int i):i(i){}
void operator+=(const Integer& arg)
{
i = i + arg.i;
}
};
//main.cpp
int _tmain(int argc, _TCHAR* argv[])
{
Integer a(10),b(20);
b += a;
}
Most of the books suggest that for the above operator overloaded function should return by reference i.e as below:
Integer& operator+=(const Integer&)
{
i = i + arg.i;
return *this;
}
If we return by reference then what happens to the return object reference when below statement is executed:
b += a;
Upvotes: 2
Views: 218
Reputation: 4386
If we return by reference then what happens to the return object reference when below statement is executed:
b += a;
Nothing really. The statement gets executed, the reference is unused and b
keep going on with its life.
This interesting stuff that returning by reference allows is chaining call: you cannot do (b += b) += a
if you don't return by reference.
This would looks like this: (void) += const Integer &
, because b += b
is of type void
due to operator+=
returning void
.
Upvotes: 3
Reputation:
So that T& x = (y += z);
works consistently with fundamental types.
Upvotes: 1