Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling base class's overloaded method [duplicate]

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]

meaning it is trying to call B's Print without considering the inherited overload. But, A's Print should be callable by a B instance. In fact, if I change the call to

bInstance.A::Print(1);

then it compiles without any errors, but I wanted to avoid having to write the class scope operator each time. Is there a way to tell the compiler I am trying to call the base class's overload of the function?

like image 797
Mic Avatar asked Mar 21 '13 19:03

Mic


1 Answers

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

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

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 the necessary modifications.

like image 110
Andy Prowl Avatar answered Nov 15 '22 14:11

Andy Prowl