Why The destructor declared virtual

House to prevent leakage.
Cause: If the application memory space in a derived class, of this memory to be released in the destructor. Suppose the non-virtual base class destructor, when deleting a base class pointer to an object of a derived class, does not trigger dynamic binding, does not call the destructor derived class. Then, the memory space of the derived class will not release memory leak occurs.

Why does not trigger dynamic binding?
The so-called dynamic binding conditions are: a pointer or reference to the base class to an object may have a different derived class. For non-virtual functions, when executing the actual object type for the call a pointer to the static function type or reference (base type); for the virtual function call object type for the actual function pointer or reference to the execution of the actual type.

Summary:
three cases (constructor and destructor call sequence):
1) the object pointer pointing to the base class is a derived class (with virtural)
configuration (created): first creating an object base class, and then create an object of a derived class;
destructor (release): to release the object of a derived class, and then releases the object base class;
2) pointer to the base class to an object of a derived class (no virtural)
configuration (created): first creating an object base class, and then create a derived object class;
destructor (release): only release the object base class;
hands 3) derived class to an object of a derived class (with virtural)
configuration (created): first creating an object base class, and then create an object of a derived class ;
destructor (release): release the first object of a derived class, and then releases the object base class;

Guess you like

Origin blog.csdn.net/QIJINGBO123/article/details/88119572