Calling the base class overload method

I have this code:

#include <iostream> #include <string> using namespace std; class A { public: void Print(int i) {cout<<i;} }; class B : public A { public: void Print(string s) {cout<<s;} }; int main() { B bInstance; bInstance.Print(1); return 0; } 

This gives me an error:

 error: invalid conversion from 'int' to 'const char*' [-fpermissive] 

means that he is trying to invoke B Print without regard to inherited overload. But A Print must be called by instance B. In fact, if I change the call to

 bInstance.A::Print(1); 

then it compiles without any errors, but I would like to avoid having to write a scope class statement every time. Is there a way to tell the compiler that I'm trying to cause an overload of the base class of a function?

+6
source share
1 answer

The Print() member function in your subclass hides the Print() member function of the superclass. Therefore, the compiler will not see A::Print() and will try to call B::Print() , complaining that int cannot be converted to a string.

To bring A::Print() to the overload set, you can enter a declaration using :

 class A { public: void Print(int i) {cout<<i;} }; class B : public A { public: using A::Print; // ^^^^^^^^^^^^^^^ void Print(string s) {cout<<s;} }; 

Here is a live example of your code, working after necessary changes.

+11
source

All Articles