Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler can't find base class method when called from derived, and the derived defines same named method with additional parameter

Here's a link to ideone with a simple code paste: http://ideone.com/BBcK3B .

The base class has a paramtereless function, whereas the derived has one with a parameter. Everything is public.

Why the compiler fails to find A::foo() when called from instance of B?

The code:

#include <iostream>
using namespace std;

class A
{
public:
    virtual void foo()
    {
        cout << "A::foo" << endl;
    }
};

class B : public A
{
public:
    void foo(int param)
    {
        cout << "B::foo " << param << endl;
    }
};

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

The compiler error:

prog.cpp: In function ‘int main()’:
prog.cpp:25:11: error: no matching function for call to ‘B::foo()’
     b.foo();
           ^
prog.cpp:25:11: note: candidate is:
prog.cpp:16:10: note: void B::foo(int)
     void foo(int param)
          ^
prog.cpp:16:10: note:   candidate expects 1 argument, 0 provided
like image 336
hauron Avatar asked Aug 07 '13 10:08

hauron


1 Answers

This is standard C++ behaviour: the base class method is hidden by a derived-class method of the same name, regardless of the arguments and qualifiers. If you want to avoid this, you have to explicitly make the base-class method(s) available:

class B : public A
{
  public:
    void foo(int param)  // hides A::foo()
    {
        cout << "B::foo " << param << endl;
    }
    using A::foo;        // makes A::foo() visible again
};
like image 76
Walter Avatar answered Oct 12 '22 22:10

Walter