Overloading rules for inheritance in C++

2019-07-09 02:58发布

问题:

The following does not compile (Apple LLVM version 4.2 (clang-425.0.28)):

class A {
public:
    virtual void foo() {};
    virtual void foo( int i ) {};
};

class B : public A {
public:
    virtual void foo( int i ) override { foo(); }
};

The compiler error is "Too few arguments" for the call to foo() inside B::foo(int). The compiler apparently thinks that I want to recursively call B::foo(int) and does not recognize that I want to call A::foo(void).

The error goes away if I replace the call to foo() by A::foo().

But:

1) Why is this happening? It seems obvious to just resolve to A::foo() in this case (or an overridden function down the class hierarchy).

2) More importantly, if I want to use polymorphic late binding for foo(void) as well, specifying A::foo() is not what I want, B::foo() of course produces a compiler error as well.

Thanks in advance for any enlightenment!

回答1:

A name in a derived class hides the same name in base classes. In other words, when resolving foo in the context of B, name lookup finds B::foo and stops there. A::foo is never found.

Add using A::foo; within B's definition.