0

My C++ lecturer claims that whenever you have to implement the operator+() you must provide operator+=() as well?

I could not understand this logic, can someone explain me the logic behind this decision?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
triple fault
  • 13,410
  • 8
  • 32
  • 45
  • It makes sense to do both if you are going to do one, but there is no "must" for this. – crashmstr Nov 13 '14 at 20:22
  • No, nothing forces you to do that it is just recommended because it is logical. – clcto Nov 13 '14 at 20:22
  • The claim is unreasonable: Z operator + (X, Y) –  Nov 13 '14 at 20:22
  • It is like whenever you use a = b + c; it is possible that you might use a = a + b; that is a += b; – Venkatesh Nov 13 '14 at 20:22
  • What your lecturer said is not true. It's _recommended_ to implement thte `+=` operator as well because users might assume a class that can use a `+` operator might also assume they can use a `+=` operator. – Coda17 Nov 13 '14 at 20:23
  • 1
    Because you may have inconsistent behavior otherwise. – πάντα ῥεῖ Nov 13 '14 at 20:23
  • For an immutable value type, you definitely should _not_ implement `+=`. For a mutable value-holding type, you usually should implement it—and, more often than not, you should implement `+` in terms of copy and `+=`. But just flat out saying "always" is misleadingly incomplete at best. The reason for that "usually" is just that most mutable types for which `+` makes sense from a user point of view, `+=` does too. After all, you can do `i += 1` for an `int`, so why not your type? – abarnert Nov 13 '14 at 20:24

1 Answers1

1

Your lecturer is wrong.

The fact that you can sum two objects forming a new third object (which is what binary + does) does not necessarily imply that your objects are supposed to be modifiable "in place" (which is what += does).

In other words, if and only if your class supports the concept of being modifiable in place, then it is a fairly good programming practice to provide += whenever you provide both + and =. But in any case there's no "must" here.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765