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
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With