Search code examples
c++operator-overloadingassignment-operator

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


Solution

  • 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.