Say we have:
Class Base
{
virtual void f(){g();};
virtual void g(){//Do some Base related code;}
};
Class Derived : public Base
{
virtual
Actually running your code shows that Derived::g() is called.
pBase is a pointer to a base. pBase = new Derived returns a pointer to a Derived - Derived is-a Base.
So pBase = new Derived is valid.
pBase references a Base, so it will look at Derived as if it were a Base.
pBase->f() will call Derive::f();
Then we see in the code that:
Derive::f() --> Base::f() --> g() - but which g??
Well, it calls Derive::g() because that is the g that pBase "points" to.
Answer: Derive::g()
The derived class' method will be called.
This is because of the inclusion of vtables within classes that have virtual functions and classes that override those functions. (This is also known as dynamic dispatch.) Here's what's really going on: a vtable is created for Base and a vtable is created for Derived, because there is only one vtable per class. Because pBase is calling upon a function that is virtual and overrode, a pointer to the vtable for Derived is called. Call it d_ptr, also known as a vpointer:
int main()
{
Base *pBase = new Derived;
pBase->d_ptr->f();
return 0;
}
Now the d_ptr calls Derived::f(), which calls Base::f(), which then looks at the vtable to see what g() to use. Because the vpointer only knows g() in Derived, that's the one we use. Therefore, Derived::g() is called.