Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading += in c++

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;
like image 698
Meir Avatar asked Nov 27 '22 22:11

Meir


2 Answers

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.

like image 101
jalf Avatar answered Nov 29 '22 11:11

jalf


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+=.

like image 28
Artem Barger Avatar answered Nov 29 '22 12:11

Artem Barger