This examples shows a derived class object being passed to a function which takes reference to base class as the parameter. Member function g(int)
in the derived class hides the g(float)
in the base class. I understand that and my question is not related to it.
class Base {
public:
virtual void g(float x) throw()
{
cout << "Base::g(float)\n";
}
};
class Derived : public Base {
public:
virtual void g(int x) throw() // Bad: Hides Base::g(float)
{
cout << "Derived::g(int)\n";
}
};
void sampleTwo(Base& b, Derived& d)
{
b.g(3.14f);
d.g(3.14f); // Bad: Converts 3.14 to 3 and calls Derived::g(int)
}
int main()
{
Derived d;
sampleTwo(d, d);
return 0;
}
Output is:
Base::g(float)
Derived::g(int)
My question is with the output "Base::g(float)". Since the object referenced by 'b' in sampleTwo() is derived object, shouldn't the dynamic binding call the g() method of the derived class (converting float to int) ?