Solution

The output is
A::f
A::g
A::f
B::g
Since this is produced by this code:
aPtr->f();
aPtr->g();
bPtr->f();
bPtr->g();
It is surprising that the pointer to the B object does not print B::f but A::f. The reason is that the derived class B hides the method A::f(), which was not declared virtual. This is known as compile-time polymorphism: at compile-time, the compiler only knows that bPtr is of type A*, and therefore binds to it the f() method found in A. The g() method, however, was declared virtual in the base class, which means that the compiler will implement run-time polymorphism (almost always the desired kind), and will delegate binding decisions (i.e. , deciding what method to call) to run-time. At run-time, even though bPtr is of type A*, it is possible to find out that in fact it points to an object of type B, so the correct binding takes place.



Leo Liberti 2008-01-12