user4578093
user4578093

Reputation: 229

implicit assignment operators

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=?

Upvotes: 0

Views: 598

Answers (3)

Pradhan
Pradhan

Reputation: 16737

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.

Upvotes: 4

Paul Rooney
Paul Rooney

Reputation: 21609

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.

Upvotes: 3

Emil Laine
Emil Laine

Reputation: 42828

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.

Upvotes: 5

Related Questions