Mr.C64 Mr.C64 - 29 days ago 15
C++ Question

Proper way of overloading binary relational operators in C++

What is the proper/canonical way of overloading binary relational operators in C++?

Is it better to use member functions, or

friend
free functions?

E.g.:

class X {
public:
...

// Use member function overloads
bool operator==(const X& rhs) const {
return m_text == rhs.m_text;
}

private:
std::string m_text;
};


or:

class X {
public:
...

// Use friend free function overloads
friend bool operator==(const X& lhs, const X& rhs) {
return lhs.m_text == rhs.m_text;
}

private:
std::string m_text;
};

Answer

It doesn't make much difference, except that

  • an instance of X needs to be on the left-hand-side of the equality operator for the member version to work. If you ever want to write

    X x("hello");
    string s("hello");
    assert(s == x);
    

    you need a non-member.

  • if you're implementing all the binary relational operators, that's a potentially large increase in your class's surface area.

    I'd generally prefer this kind of auxiliary interface to be kept apart from the main class logic where possible (unless, of course, your class's primary concern is comparison).

    Using non-friend free operators and a minimal public interface is perhaps even better.