Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism not working if overloaded functions are being overridden only partially

Today I felt like a noob:

class Base
{
public:
    virtual void foo(int)=0;
    virtual void foo(int, int) {}
    virtual void bar() {}
};

class Derived : public Base
{
public:
    virtual void foo(int) {}
};

void main()
{
    Derived d;
    d.bar(); // works
    d.foo(1); // works
    d.foo(1,2); // compiler error: no matching function call
}

I expected d to inherit foo(int, int) from Base, but it does not. So what am I missing here?

like image 416
Alexander Tobias Bockstaller Avatar asked Aug 24 '12 16:08

Alexander Tobias Bockstaller


2 Answers

That's because the base functions with the same name are hidden.

You'll need to use using for the function you're not overriding:

class Derived : public Base
{
public:
    using Base::foo;
    virtual void foo(int) {}  //this hides all base methods called foo
};
like image 198
Luchian Grigore Avatar answered Sep 28 '22 07:09

Luchian Grigore


It's called Name hiding. You hide Base::foo(int, int) by providing Derived::foo(int)

like image 27
Andrew Avatar answered Sep 28 '22 09:09

Andrew