Timur Timur - 1 month ago 6
C++ Question

How to inherit some candidates of polymorphic function?

I want to define a function in a base class and a function with the same name and another signature in a subclass like this:

class A {
public:
void foo () {}
};

class B : public A {
public:
void foo(int x) {}
};

int main() {
B b;
b.foo();
}


But it causes compile error:
no matching function for call to ‘B::foo()’
.
If I comment
foo
definition in class B, it compiles.
How to solve the problem?

What I really want is to define a polymorhic interface in a base class and redefine semantic in child classes.

Answer

Without virtual, the A::foo() doesn't define a polymorphic interface.

Anyway, you can make A::foo() visible via B with a using declaration:

class B : public A {
public:
  using A::foo;
  void foo(int x) {}
};

This provides polymorphism to the extent that you accept function overloading as polymorphism--i.e., A::foo() and B::foo() form an overload set, and the compiler chooses which to call based on the parameter(s) you pass (if any), the same way as if B contained two overloaded functions (with the same signatures as the existing A::foo and B::foo).