I've got the following code with output. I can't figure out myself why it's what printed out there. I believe, it has something to deal with overloading/overriding/virtual functions implementations in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Base{
public: virtual void f(int);
virtual void f(double);
}
void Base::f(int) {cout << "Base::f(int)" << endl;}
void Base::f(double) {cout << "Base::f(double)" << endl;}
class Derived : public Base{
public: void f(int);
}
void Derived::f(int) {cout << "Derived::f(int)" << endl;}
int main(void){
Base b;
Derived d;
Base* pb = new Derived;
b.f(1.0);
d.f(1.0);
pb->f(1.0);
delete pb;
}
|
Here's the output:
Base::f(double); // this is simple
Derived::f(int); // why it's not 'Base::f(double)'
Base::f(double); // let's accept the previous answer. Then: why it's not 'Derived::f(int)'
|
After debugging in MS VS 2010 I've found, that:
b is object with vfPtr pointing to vfTable, consisting from 2 virtual functions:
Base::f(double)
Base::f(int)
d is object with vfPtr pointing to vfTable, consisting from 2 virtual functions:
Base::f(double) // this wasn't overrided
Derived::f(int) // this is overriding function
Thus here're my conclusions:
1) in line
d.f(1.0);
for some reason compiler preferred casting double->int of the argument and then call to 'Derived::f(int)'.
2)in line
pb->f(1.0);
for some reason compiler preferred call to 'Base::f(double);'. 'Base' is static type of pb, but the dynamic type is 'Derived'.
I believe the answer has to deal with the fact whether virtual table contains in addition to functions' names also the types of arguments they accept. AFAIK, vTable doesn't include such info.
Any help would be greatly appreciated.