Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a pure virtual function using a subclass reference in the overriden function

So I have a problem to override a pure virtual function in my derived class. The implementation and declaration of the classes looks like this:

class Base{
private:
   size_t id;
public:
   virtual bool isEqual(const Base& src) const =0;
};

class Derived: public Base{
private:
    string str;
public:
    virtual bool isEqual(const Derived& src) const override
    {
        return (this->str == src.str);
    }
};

so when I implement it like this it hits me with compiler error like

member function declared with 'override' does not override a base class member function

Could you plz tell me how I could get that right and maybe explain me why my version doesn't work. Thanks in advance!

like image 979
Vissarion Moutafis Avatar asked Oct 27 '25 06:10

Vissarion Moutafis


1 Answers

You cannot change the function signature that way – read about co- and contravariance for details and why C++ disallows both for function parameters (covariant return types are allowed).

On the other hand, if the other object is referred to via reference to base, the overriding (actually: overloading!) function would not be called at all:

Derived d1;
Derived d2;
Base& b2 = d2;

d1.isEqual(b2); // how do you imagine the derived version to get called now???

Key to a solution is a dynamic_cast:

struct Base
{
    virtual ~Base() { }
    virtual bool operator==(Base const& other) = 0;
};

struct Derived : Base
{
    bool operator==(Base const& other) override
    {
        auto o = dynamic_cast<Derived const*>(&other);
        return o && o->str == this->str;
    }
};

Note that I renamed the function to operator==; this is far more natural in C++. With that, you can compare in the example above with:

bool isEqual = d1 == b2;

Edit:

The teacher told us that we must not overload operator

Well, then just revert the renaming... Actually, operators are just as ordinary functions as any other one else, solely that calling syntax differs (actually: an alternative variant exists, you could always call as d1.operator ==(d2), too).

like image 104
Aconcagua Avatar answered Oct 29 '25 20:10

Aconcagua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!