1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <iostream> using namespace std; class Base { public : virtual void doSomething( double a) { cout << "This is double from Base: " << a << endl; } virtual void doSomething( int a) { cout << "This is int from Base: " << a << endl; } virtual ~Base() {} }; class Derived : public Base { public : virtual void doSomething( double a) { cout << "This is double from Derived: " << a << endl; } virtual ~Derived() {} }; int main() { Derived d; int i = 2; double j = 0.1; d.doSomething(i); d.doSomething(j); return 0; } |
This is int from Base: 2 This is double from Derived: 0.1
Strangely, the output is:
This is double from Derived: 2 This is double from Derived: 0.1
The way overload resolution works in C++ is that the compiler will first search for function doSomething() inside the Derived class. If it finds it, it will stop there; otherwise it will look the one in the Base class for a matching function. To solve this problem, we need to add using Base::doSomething in order let it participate in the overload resolution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <iostream> using namespace std; class Base { public : virtual void doSomething( double a) { cout << "This is double from Base: " << a << endl; } virtual void doSomething( int a) { cout << "This is int from Base: " << a << endl; } virtual ~Base() {} }; class Derived : public Base { public : virtual void doSomething( double a) { cout << "This is double from Derived: " << a << endl; } using Base::doSomething; virtual ~Derived() {} }; int main() { Derived d; int i = 2; double j = 0.1; d.doSomething(i); d.doSomething(j); return 0; } |
The output is:
This is int from Base: 2 This is double from Derived: 0.1