The g of the derived class will be called. If you want to call the function in the base, call
Base::g();
instead. If you want to call the derived, but still want to have the base version be called, arrange that the derived version of g calls the base version in its first statement:
virtual void g() {
Base::g();
// some work related to derived
}
The fact that a function from the base can call a virtual method and control is transferred into the derived class is used in the template method design pattern. For C++, it's better known as Non-Virtual-Interface. It's widely used also in the C++ standard library (C++ stream buffers for example have functions pub...
that call virtual functions that do the real work. For example pubseekoff
calls the protected seekoff
). I wrote an example of that in this answer: How do you validate an object’s internal state?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…