views:

353

answers:

4

If I've overloaded operator+ and operator= do I still need to overload operator+= for something like this to work: -?-

MyClass mc1, mc2; mc1 += mc2;

+7  A: 

Yes, you do.

Eric
+6  A: 

operator+= is not a composite of + and =, therefore you do need to overload it explicitly, since compiler do not know to build puzzles for you. but still you do able to benefit from already defined/overloaded operators, by using them inside operator+=.

Artem Barger
+25  A: 

Yes, you need to define that as well.

A common trick however, is to define operator+=, and then implement operator+ in terms of it, something like this:

MyClass operator+ (MyClass lhs, const MyClass& rhs){
  return lhs += rhs;
}

If you do it the other way around (use + to implement +=), you get an unnecessary copy operation in the += operator which may be a problem i performance-sensitive code.

jalf
Old, I know, but it's better just to take `lhs` by value instead of doing the copy manually.
GMan
@GMan: You're right. Wonder why I didn't do this the first time around. Consider it fixed. :)
jalf
@jalf: And if you want to be really terse, `return lhs += rhs;`. :)
GMan
@GMan: pf, now you're just showing off. It's not fair to correct my code right now. I'm busy panicking over my masters' thesis! Can't expect me to write sensible code at the moment! ;) (Also, fixed)
jalf
@jalf: Get back to work! :)
GMan
@GMan: IIRC, I was once shown that `return lhs += rhs;` might be a pessimization, since it's harder for the compiler to figure out that `+=` returns `lhs`, which makes it hard to apply RVO. That was ten years ago and maybe compilers are clever enough to do this, but I will cling to `lhs += rhs; return lhs;` just in case. And, @jalf, Good luck with that!
sbi
+2  A: 

If the real question here is, "I don't want to write a load of repetitive operators, please tell me how to avoid it", then the answer may be:

http://www.boost.org/doc/libs/1_38_0/libs/utility/operators.htm

The syntax looks a little fiddly, though. As I've never used it myself, I can't reassure you that it's simple really.

Steve Jessop