In a derived class, if you create a function with the same name as one in the base class, even with a different argument type, is the base class function no longer usable in the derived class?
A simplified version of my problem is given below.
In practical use I have a base Bitmap class which loads from a filename string and a derived class for Windows Bitmaps which also loads them from bitmap handles, hence the types of variables I'm testing here.
#include <iostream>
#include <string>
#include <windows.h>
usingnamespace std;
class A {
protected:
string str;
public:
//Load from string
void load(const string& filename) {
str = filename;
}
string getString() const {
return str;
}
};
class B : public A {
public:
//Load from Win32 bitmap handle
void load(HBITMAP hbm) {
//Just a trivial do-nothing function for now
str = "HBITMAP";
}
};
int main() {
//Create test variables
HBITMAP hbm = NULL;
string str = "hello";
//Create test instances
A a;
B b;
//Load base class from string
a.load(str);
//Load derived class from string
b.load(str); //Now, the base class function fails
//And from handle
b.load(hbm); //This works as expected
//Pause before exiting
cin.get();
return 0;
}
The error I get in Dev-C++ is: no matching function for call to `B::load(std::string&)'
candidates are: void B::load(HBITMAP__*)
I then modified the derived class do the following, and it works fine.
1 2 3 4 5 6 7 8 9 10
class B : public A {
public:
void load(const string& filename) {
//Explicitly call the base class method
A::load(filename);
}
void load(HBITMAP hbm) {
str = "HBITMAP";
}
};
Now, I had expected the base class function to still be valid, since the new function takes a different argument type. Clearly, I was wrong. Can anyone explain this behavior to me? Thanks!
Thanks - I don't have the patience to comb through standards... But then, what is the logical reason for the standard doing this - is it just not possible for C++ to implement inheritance in this way (probably would be beyond my current comprehension), or is the standard intended in this case just to prevent the programmer from doing some specific harmful thing in his code?
Base::foo(double i) {
//....
}
Derived::foo(int i) {
//....
}
Derived d;
d.foo(2.0f); //which function do we call?
//or do we just give an error even though we could convert?