Chris Tonkinson
Chris Tonkinson

Reputation: 14459

Inheritance mucking up polymorphism in C++?

Perhaps my knowledge of inheritance and polymorphism isn't what I thought it was. Can anyone shed some light?

Setup (trivialization of problem):

class X {
};

class Y {
};

class Base {
  public:
    void f( X* ) {}
};

class Child: public Base {
  public:
    void f( Y* ) {}
};

Question: This should work, right?

int main( void ) {
  X* x = new X();
  Y* y = new Y();
  Child* c = new Child();
  c->f( x );
  c->f( y );
  return 0;
}

I get errors (GCC 4.4) to the tune of:

`no matching function for call to 'Child::f(X*&)'`
`note: candidates are: void Child::f(Y*)`

Upvotes: 0

Views: 513

Answers (3)

J. Calleja
J. Calleja

Reputation: 4905

It was already answered at:

Why does an overridden function in the derived class hide other overloads of the base class?

When you declare a method on a derived class, it hides any method with the same name from the base class.

Upvotes: 0

sbi
sbi

Reputation: 224029

Your derived class' f() hides the base class' f(). You can prevent this by explicitly bringing Base::f() into the derived class' scope:

class Child: public Base {
  public:
    using Base::f;
    void f( Y* ) {}
};

Upvotes: 2

Brian R. Bondy
Brian R. Bondy

Reputation: 347196

The virtual keyword will not help you here.

Your base class Base::f is being hidden by your derived type. You need to do the following:

class Child: public Base {
  public:
    using Base::f;
    void f( Y* ) {}
};

Parashift goes into more detail.

Upvotes: 9

Related Questions