c++inheritanceoperator-overloading

C++ nonmember binary operator with private inheritance


As has been pointed out elsewhere, the community thinks C++ binary operators like == should be nonmember functions. This presents a problem for me with private inheritance.

#include <cassert>

class Parent
{
public:
    Parent(int arg = 0) {}
    int member() const { return member_; }
private:
    int member_;
};

bool operator== (const Parent& a, const Parent& b) { return a.member() == b.member(); }

class Child : private Parent
{
public:
    Child(int arg = 0) : Parent(arg) {}
};

bool operator== (const Child& a, const Child& b)
{
    return static_cast<const Parent&> (a) == static_cast<const Parent&> (b);
}

int main()
{
    assert(Child(1) == Child(1));
}

Having Child's operator== call Parent's is trivial if operator== is a member, but done this way, C++ complains that conversion from Child to Parent is inaccessible (as it should be).

Does the community have a fix, or do I do my own hack?


Solution

  • The most common way of doing this is to write a normally-named member function that implements the predicate; the binary operator just calls that function.

    struct parent {
    
        bool equals(const parent& other) const {
            return _member == other._member;
        }
    
    };
    
    bool operator==(const parent& lhs, const parent& rhs) {
        return lhs.equals(rhs);
    }
    
    struct child : private parent {
    
        bool equals(const child& other) const {
            return parent::equals(other);
        }
    
    };
    
    bool operator==(const child& lhs, const child& rhs) {
        return lhs.equals(rhs);
    }