1

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?

5Pack
  • 313
  • 1
  • 9

2 Answers2

4

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

Jason
  • 36,170
  • 5
  • 26
  • 60
1

How about this:

int main() {
    Special s;
    s.print(3);  // want to print from Special
    s.General::print();  // want to print from General
}
wohlstad
  • 12,661
  • 10
  • 26
  • 39