I'm trying to compile next code in Visual Studio 2010:
A {
public:
void f(int i) {cout << i;}
};
class B: public A {
public:
void f(string s) {cout << s;}
};
void main() {
A a;
B b;
a.f(1);
b.f("zazaza");
b.f(1); //Compilation fail
}
But compilation fails. I cannot understand why I cannot call f(int) from parent class. What should I do to fix this problem?
The void f(string); in the derived class is hiding the parent's same name method, not overriding it. You can use using keyword in the derived class to un-hide it.
class B: public A
{
public:
using A::f;
//^^^^^^^^^
void f(string s)
{
cout << s;
}
};
Now, both two f methods are overloads to each other and the f(int) is avaiable.
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