If a base class has a destuctor, but sub class doesn’t have, compiler
will produce an implicit default destructor, and this implicit
default destructor will call base class destuctor.
If you define a subclass destructor, It will call base destructor
automaticlly, you don’t need to call it explicitly.
The question is, How can you make sure you sub class destructor
will be called if you use a base class pointer or reference, answer
is below:
Don’t call base desctructor explicitly, It will called automatically in the
reverse order of construction. And you should give a base desctructor a
definition, Or linker will report error it even you don’t call it in your source
code.
Make base class destructor public and virtual (polymorphic deletion by base
class pointer or reference), or proteced and nonvirtual, base classes need not
always allow polymorphic deletion. For example, consider class templates
such as std::unary_function. This time, you should make destructor
protected and nonvirtual.
If base class still need to build itself, You can change it back public virtual,
Even without polymorphic deletion by now, you still need to declare it as
virtual for the future safety(Even with a little dynamic-binding efficiency
penalty. ) At same time, If a base class is not abstract class, usually, it’s
BAD design.
Never throw exception from dtor, if exception A is thrown, then
stack-unwindling, when a obj is destructed, then dtor is called, when
another exception B is thrown by the dtor, application will call terminat
function immediately. If you have exception, catch it inside of the
dtor.