Given the following...
#include <iostream>
using namespace std;
class BaseClass {
public:
void Func(float f) {
cout << "BaseClass:Func() called!";
}
};
class SubClass : public BaseClass {
};
int main() {
SubClass sub;
sub.Func(1.1f);
return 0;
}
This runs pretty much as one would expect, resulting in the following output...
BaseClass:Func() called!
However, if I add the following function to SubClass...
class SubClass : public BaseClass {
public:
void Func(int i) { // accepts an int, not a float!
cout << "SubClass::Func() called!";
}
};
Like any other overload, I would expect the SubClass function to be called if I supply an int as my argument, and BaseClass's if I supply a float. However, if I run the program as-is (ie. with the float), this is not the case...
SubClass::Func() called!
Instead of what I was expecting, the float I provided is cast to an integer, and the SubClass function is called. It seems SubClass's function effectively shadows BaseClass's function, even though its signature differs.
Can someone shed some light on this? Is there a way to call the BaseClass function via a SubClass instance without having to cast it?
Thanks!
As you said, the BaseClass
's function is hidden by the SubClass
's. The name Func
will be found at the SubClass
's scope, then name lookup stops, Func
in BaseClass
won't be considered at all, even it's more appropriate. They're not "overloads" at all.
You can use using
to introduce them into the same scope to make overloading works.
class SubClass : public BaseClass {
public:
using BaseClass::Func;
~~~~~~~~~~~~~~~~~~~~~
void Func(int i) { // accepts an int, not a float!
cout << "SubClass::Func() called!";
}
};