1

When I overload, lets say, the '+' operator for a class in C++

MyClass MyClass::operator+(MyClass _c){
    //code here
}

Does it automatically apply to the '+=' operator? Does the compiler automatically substitute that for its longer conuterpart (a+=b <--> a=a+b)? Or is it a runtime operator function?

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
J3STER
  • 1,027
  • 2
  • 11
  • 28
  • 1
    It does not. At least MSVC++ compiler seems to think its not valid. – jumper0x08 Jan 28 '17 at 05:05
  • 1
    Writing an `operator+=` in terms of `operator+` sounds very expensive - create a temporary LHS from this, add RHS, then assign the result temporary to this. It would be a bit simpler the other way round - write `operator+=` and implement `operator+` in terms of it. – Kos Jan 28 '17 at 05:52
  • Also, conventionally, an `operator+()` changes neither of its operands (i.e. `a+b` changes neither `a` nor `b`). This can be expressed by use of `const`. – Peter Jan 28 '17 at 06:46
  • In C++, you typically write the += operator in all it's glory, and then write: `foo operator +(foo lhs, const foo& rhs) { return lhs+= rhs; }`. That is a free-standing function, not a member function, and note that `lhs` is passed by *value*. (It's important not to make it a member function, because otherwise `aBar + aFoo` (where `bar` implicitly converts to `foo`) won't compile; – Martin Bonner supports Monica Jan 28 '17 at 08:13
  • I didint mean to ask if it automatically overloaded it with the same function, but if the compliler automatically replaced a+=b with a = a + b; that would be really simple, and should that be the case, the answer would be YES – J3STER Jan 28 '17 at 15:54

1 Answers1

3

No. It doesn't. You need to overload those as well.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173