Item 07-Declaring the virtual destructor for the polymorphic base class
Declare destructors virtual in polymorphic base class
Why? http://blog.csdn.net/wxqian25/article/details/7361069
Ex: There are several ways to record time, a base class and some derived classes
Class timekeeper{//base class
Public
Timekeeper ();
~timekeeper ();
...
}
Class Atomicclock:public timekeeper{...} Atomic clock derived class
Class Waterclock:public timekeeper{...} Hourglasses derived class
Class Wristclock:public timekeeper{...} Watches derived class
int main ()
{
Atomicclock *p1 = new Atomicclock ()//derived class
Delete P1; base class, destructors for derived classes are executed
Timekeeper *p2 = new Atomicclock ()//base class
Delete P2; the base class destructor was executed, but the derived class destructor was not executed!!! , it will cause a memory leak!!!
}
Workaround: Give base Class A virtual destructor, then execute the derived class destructor, which is virtual ~timekeeper ();
Virtual functions are the mechanisms used in C + + to implement polymorphism, and the core idea is to access the functions defined by the derived class through the base class. (polymorphic effects can only be achieved with pointers or references)
A virtual destructor is declared for a class if there is at least one virtual function within it.
How the destructor works: the class of the deepest derivation (most derived) whose destructor is called First, followed by the destructor of each of its base class.
Please remember:
1, "To base classes a virtual destructor" this rule applies only with polymorphic (with polymorphic nature) base classes body. This base classes is designed to be used to process derived class objects through the base class interface.
2. polymorphic (with polymorphic properties) base class should declare a virtual destructor, and if class has any virtual functions, it should have a virtual destructor.
3, classes design if not used as base classes, or not for polymorphism (polymorphically), the virtual destructor should not be declared.
Effective C + + Item 07-declares a virtual destructor for the polymorphic base class