Say we have:
Class Base
{
virtual void f(){g();};
virtual void g(){//Do some Base related code;}
};
Class Derived : public Base
{
virtual void f(){Base::f();};
virtual void g(){//Do some Derived related code};
};
int main()
{
Base *pBase = new Derived;
pBase->f();
return 0;
}
Which g()
will be called from Base::f()
? Base::g()
or Derived::g()
?
Thanks...
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()
As you have defined g() to be virtual, the most derived g() will be looked up in the vtable of the class and called regardless of the type your code is currently accessing it.
See the C++ FAQ on virtual functions.
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 forDerived
, because there is only one vtable per class. BecausepBase
is calling upon a function that is virtual and overrode, a pointer to the vtable forDerived
is called. Call itd_ptr
, also known as a vpointer:Now the d_ptr calls
Derived::f()
, which callsBase::f()
, which then looks at the vtable to see whatg()
to use. Because the vpointer only knowsg()
inDerived
, that's the one we use. Therefore,Derived::g()
is called.Well... I'm not sure this should compile. The following,
is invalid unless you have:
Is it want you meant? If this is want you meant,
Then the call stack would go like this:
Actually running your code shows that Derived::g() is called.
I think you trying to invent Template Method Pattern