2

When compiling the following code :

class Base {
public:
    Base(){}
    virtual ~Base(){}
    virtual bool equals(const Base* rhs) const { return false;}
};

class DerivedA : public Base {
public:
    DerivedA() : Base(), val(0) {}
    virtual ~DerivedA() {}
    virtual bool equals(const DerivedA* rhs) const { return this->val == rhs->val;}
    int val;
};

class DerivedB : public Base {
public:
    DerivedB() : Base(), val(0) {}
    virtual ~DerivedB() {}
    virtual bool equals(const DerivedB* rhs) const { return this->val == rhs->val;}
    int val;
};

int main() {
    const DerivedA a;
    const DerivedB b;

    std::cout << a.equals(&b);
}

I get:

../main.cpp:104:26: error: no matching function for call to ‘DerivedA::equals(const DerivedB*) const’
std::cout << a.equals(&b);
                       ^
../main.cpp:104:26: note: candidate is:
../main.cpp:88:15: note: virtual bool DerivedA::equals(const DerivedA*) const
virtual bool equals(const DerivedA* rhs) const { return this->val == rhs->val;}
             ^
../main.cpp:88:15: note:   no known conversion for argument 1 from ‘const DerivedB*’ to ‘const DerivedA*’

But why doesn't it use the base class virtual bool equals(const Base* rhs) const?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
thedimitrius
  • 148
  • 1
  • 11

1 Answers1

2
bool DerivedA::equals(const DerivedA* rhs) const

is not an override of

bool Base::equals(const Base* rhs) const

but an other overload (as you may notice with override) which hides the base method.

If you just want to 'unhide' base method, you may add

using Base::equals;

into your derived class.

But to really solve your issue, you have to use multiple dispatch.

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 1
    Indeed, that's not an override, that's overload. So, I expect both functions to be visible. For example, if I add bool equals(int a) { return a == val;} to the base class, it is visible if I access it from a variable of type Base*, but not DerivedA*. – thedimitrius Sep 13 '15 at 12:32
  • Thanks for the answer, Jarod42, and thanks for the edit, Captian Giraffe. It's really a "name hiding" feature of C++. Usiing "using" helped to solve it. – thedimitrius Sep 13 '15 at 12:42