In C ++, the virtual keyword is added to the function to realize polymorphism. Polymorphism can be used to change the implementation of an interface. It is also a means of embedding application-layer code to the underlying implementation. Even if you don't use the Complex C ++ technologies, polymorphism will certainly be used.
However, adding virtual does not necessarily guarantee the success of polymorphism:
# Include <stdio. h>
Class Base {
Public:
Base (){
Init ();
}
Virtual ~ Base (){
Release ();
}
Virtual void Init (){
Printf ("Base: Init \ n ");
}
Virtual void Release (){
Printf ("Base: Release \ n ");
}
};
Class Derived: public Base {
Public:
Virtual void Init (){
Printf ("Derived: Init \ n ");
}
Virtual void Release (){
Printf ("Derived: Release \ n ");
}
};
Int main ()
{
Base * obj = new Derived ();
Delete obj;
Return 0;
}
When a virtual function is called in the constructor, including the destructor, the expected polymorphism cannot be completed. The output result of the above Code is:
Base: Init
Base: Release
From the perspective of language design, I personally do not accept such behavior. I think almost all features of a language should be the same, and such "exceptions" should not or should be minimized. What is the difference between constructing an object in different ways and changing its behavior? (From this sentence, there seems to be a difference)
Of course, from the perspective of language implementation, such running results seem inevitable. Because the construction of the base class is earlier than that of the derived class (as part of it). Only after the derived class is constructed can the virtual table that supports polymorphism be correctly constructed. That is to say, when a virtual function is called in the base class, since the virtual table is correctly constructed, the virtual function of the derived class will not be called. According to the order of the structure, the Destructor will also face the same situation.