I have overloaded the operator + by Integer operator+(Integer & a, Integer & b). But when I do a=b+c+d, it gives the error of invalid operands to binary expression. But by adding const to the parameters, no more errors. Why this happens?
Asked
Active
Viewed 993 times
1
Bruce Jinru Su
- 189
- 6
- 14
1 Answers
7
b + c + d generates a temporary for the result of b + c. A reference to that temporary is then passed to the second call to operator+().
Only const references can be bound to temporaries.
For further discussion, see How come a non-const reference cannot bind to a temporary object?