Why should I overload a C++ operator as a global function (STL does) and what are the caveats?

unixman83 picture unixman83 · Sep 28, 2011 · Viewed 7.2k times · Source

Why would I want to overload a C++ operator() as global and not member function. For example, the == operator.

Why is this done? for example in STL libraries.

Answer

James Kanze picture James Kanze · Sep 28, 2011

The usual rule is for operators which modify the left hand object to be members, and binary operators which return a new object to be free functions; the main motivation for the latter is because the compiler will not convert the left hand side to match a member; if your class supports any implicit conversions, then all of the usual binary operators should be free functions, so that the same rules of conversion apply
for the left hand side and the right hand side, e.g.:

class Complex
{
public:
    Complex(double r, double i = 0.0);
    bool operator==( Complex const& other ) const;
};

Complex a;
//  ...
if ( a == 1.0 ) // OK
//  ...
if ( 1.0 == a ) // error.

but:

class Complex
{
public:
    Complex(double r, double i = 0.0);
    friend bool operator==( Complex const& lhs, Complex const& rhs ) const;
};

Complex a;
//  ...
if ( a == 1.0 ) // OK
//  ...
if ( 1.0 == a ) // OK

One elegant way of achieving this is to define the basic operations in terms of member functions—for things like + or -, these would be operator+= and operator-=; for comparison, you'd need to define an arbitrary conventions, a member isEqual, or compare (which would return <, == or > zero according to the results, then inherit from a template along the lines of:

template <typename T>
class ArithmeticOperators
{
    friend T operator+( T const& lhs, T const& rhs )
    {
        T result( lhs );
        result += rhs;
        return result;
    }
    //  And so on, for all of the binary operators.
};

class Complex : public ArithmeticOperators<Complex>
{
public:
    //  ...
    Complex& operator+=( Complex const& other );
    //  etc.
};

Note that there is some argument for making the operator <op>= functions free functions as well: the fact that the free function will take a non-const reference as its first argument, and thus requires an lvalue (like the built-in operator <op>=). This doesn't seem to be the usual practice, however, probably because operator= must be a member, and it seems more natural to treat the operator <op>= in the same mannter.