1

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?

Bruce Jinru Su
  • 189
  • 6
  • 14

1 Answers1

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?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012