Timur Timur - 1 year ago 59
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 {
void foo () {}

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

int main() {
B b;

But it causes compile error:
no matching function for call to ‘B::foo()’
If I comment
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 Source

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 {
  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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download