'Polymorphism by method parameters split across base and inherited classes [duplicate]

I have the following:

#include <iostream>

using std::cout;

class General {
    public:
        General() {};

        void print(void) {
            cout << "From General\n";
        }
};

class Special : public General {
    public:
        Special() {};

        void print(int c) {
            cout << "From Special\n";
        }
};

int main() {
    Special s;
    s.print(3);  // want to print from Special
    s.print();  // want to print from General
}

The output that I would like to see is:

From Special
From General

However, I get this compilation error (referring to the very last print() call):

error #165: too few arguments in function call

I want the compiler to recognize which print method to call based on the number and types of arguments I provide. If these 2 methods were defined within the same class, then it would work perfectly. But here, they are split across the base and derived classes.

Is there a way to do this?



Solution 1:[1]

You can achieve this by adding a using declaration inside Special as shown below. This works because a using declaration for a base-class member function(like print in your case) adds all the overloaded instances of that function to the scope of the derived class.

class Special : public General {
    public:
        Special() {};
//------vvvvvvvvvvvvvvvvvvv-->added this using declaration
        using General::print;
        void print(int c) {
            cout << "From Special\n";
        }
        
};

Demo

Solution 2:[2]

How about this:

int main() {
    Special s;
    s.print(3);  // want to print from Special
    s.General::print();  // want to print from General
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 wohlstad