In this program in the operator overloading of += the return type is a reference.
My question is that if we simply return an object instead of returning a reference the program output is wrong...
Why is it so???
Ugh. Setting aside that you should never do this crap... here's what's happening:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// when you return a reference.... the returned value IS the left-hand value.
// ie, when you return *this, the returned value is actually the same object that 'this'
// points to.
// when you return by value, the returned value is a COPY of 'this'
// with reference:
// (c1+=c2+=c3)=c4; <- this... expands to this:
c2 += c3;
c1 += c2;
c1 = c4;
// returning by value... it expands to this:
c2 += c3; __tempcopy = c2;
c1 += __tempcopy; __tempcopy = c1;
__tempcopy = c4;
As you can see... when you return by value, the final assignment is actually assigning to a temporary copy, and not assigning to c1. Hence the discrepancy.