0

If I have an operator overload on my class, is the assignment version of the operator implicitly created as well?

class square{
   square operator+(const square& B);
   void operator=(const square& B);
};

As in, can I then call

square A, B;
A += B;

with the compiler implicitly deciding to call operator+ then operator=?

Yun
  • 3,056
  • 6
  • 9
  • 28
user4578093
  • 231
  • 1
  • 3
  • 10
  • Operator overloading is one of the best ways of making code unreadable. According to the [Google C++ Style Guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.html#Operator_Overloading): "In general, do not overload operators. You can define ordinary functions like Equals() if you need them." – msw Mar 07 '15 at 21:44
  • 1
    It is so much nicer though, when creating classes that are to be used to represent numbers to be able to read the code in a familiar format, it is a matter of; A = A.add(B).div(C).mul(D) vs A = (A + B) / C * D – user4578093 Mar 08 '15 at 05:56

3 Answers3

5

No, += must be defined explicitly.


As a side note, operator+ should usually create a new object:

square operator+(const square& B);

And operator= should return a reference to *this:

square& operator=(const square& B);

Also worth noting that operator+ is usually implemented in terms of operator+=, i.e. operator+ calls operator+= on the new copy.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
4

No, the operators aren't implicitly defined. However, boost/operators.hpp defines useful helper templates to avoid boiler-plate code. Example from their docs :

If, for example, you declare a class like this:

class MyInt
    : boost::operators<MyInt> {
    bool operator<(const MyInt& x) const;
    bool operator==(const MyInt& x) const;
    MyInt& operator+=(const MyInt& x);
    MyInt& operator-=(const MyInt& x);
    MyInt& operator*=(const MyInt& x);
    MyInt& operator/=(const MyInt& x);
    MyInt& operator%=(const MyInt& x);
    MyInt& operator|=(const MyInt& x);
    MyInt& operator&=(const MyInt& x);
    MyInt& operator^=(const MyInt& x);
    MyInt& operator++();
    MyInt& operator--(); };

then the operators<> template adds more than a dozen additional operators, such as operator>, <=, >=, and (binary) +. Two-argument forms of the templates are also provided to allow interaction with other types.

In addition, there is also support for implicitly "deducing" just a specific set of operators using arithmetic operator templates.

Pradhan
  • 16,391
  • 3
  • 44
  • 59
3

No operator+= is its own operator and must be defined explicitly.

Note that operator+ should return a new object rather than a reference to the original object. The original object should be left unchanged.

operator+= should return the original object with the required value added. operator+= is often preferable as it eliminates a temporary object.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61