Electric Coffee Electric Coffee - 1 month ago 8
C++ Question

Overriding an operator to use the derived class in C++

I'm trying to override a virtual comparison operator in a sub-class, but I'm getting a compiler-error saying the derived class doesn't implement the base class' virtual operator.

I have a feeling it's to do with the fact that my derived operator doesn't use the base class' argument type.

A simplified version goes as follows:

struct Base {
virtual bool operator ==(const Base) const;
};

struct Derived : Base {
bool operator ==(const Derived) const {
// implementation goes here
}
};


Is there a way for me to do this, or do I have to do a type check in the
Derived
implementation to see if it's the right type?

Answer

I have a feeling it's to do with the fact that my derived operator doesn't use the base class' argument type.

Exactly so. The base class must take a const reference (so that it can have dynamic type Derived, and then you declare the override as:

bool operator ==(const Base& rhs) const {
    const auto pRhs = dynamic_cast<const Derived*>(&rhs);
    if (pRhs == nullptr)
    {
        return false;  // Not a derived.  Cannot be equal.
    }
    // Derived/Derived implementation goes here
}

Beware though: A virtual comparison operator like this is very easy to get wrong. You need a good motivating example to do it like this. In particular, if you write:

Derived d;
Base b;
if (d == b)  // All is well - derived override called, and returns false.

if (b == d) // Uh-oh!  This will call the *base* version.  Is that what you want?

Also:

Derived d;
DerivedDerived dd;

if (d == dd) // Did you want to use the DerivedDerived comparison?