9

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
hauron
  • 4,550
  • 5
  • 35
  • 52

1 Answers1

15

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
};
Walter
  • 44,150
  • 20
  • 113
  • 196
  • This is a complete answer, although I guess I had hoped a bit for explanation "why is that so?". Anyway this answers my questions, thanks. – hauron Aug 07 '13 at 11:28
  • @hauron Those *why is this so?* questions are not very helpful and may even be off topic on SO. The point is that there are many answers that you don't want to hear, such as *because the the author(s) of C++ thought this was desirable*. – Walter Mar 22 '19 at 07:36
  • Yes, but we can go a step further: why did the authors of C++ think this was desirable? I would assume a bit of context is well within the scope of SO. – hauron Mar 22 '19 at 10:04
  • 1
    @hauron I agree, but then ask more specifically. – Walter Apr 05 '19 at 05:35
  • 1
    good point. As a side-note: it's kinda funny, that we've had this conversation over 6 years. Have a nice day ;-) – hauron Apr 05 '19 at 08:22