Effective C++ item 7: Declare destructors virtual in polymorphic base classes.

  1. Polymorphic base classes should declare virtual destructors. If a class has any virtual functions, it should have a virtual destructor.
  2. Classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors.
    For the first point, if the base class doesn’t have a virtual destructor, there are great potential that you will have memory leak in your program. Here is an example.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    class Base
    {
    public:
    Base();
    ~Base();
    ...
    };
    Derived derived;
    Base* base = derived.get();
    delete base;

Consider here get() method returns a pointer to a dynamically allocated object, and if we delete Base class pointer with a non-virtual destructor, results are undefined. What typically happens at runtime is that the derived part of the object is never destroyed. This is an excellent way to leak resources, corrupt data structures, and spend a lot of time with a debugger. So any class with virtual functions should almost certainly have a virtual destructor.

Sometimes, you have class that you’d like to be abstract, but you don’t have any pure virtual functions. What to do? The solution is simple: declare a pure virtual destructor in the class you want to be abstract. But you must provide a definition for the pure virtual destructor! Because the way destructors work is that the most derived class’s destructor is called first, then the destructor of each base class is called. The compilers will generate a call to the destructor of a base class from its derived classes’ destructors, so you have to be sure to provide a body for the function. If you don’t, the linker will complain.

For the second point, because virtual function needs extra space to store virtual table and other stuff, it will not be efficient to use virtual functions in classes are not designed to be polymorphic. In addition, it may cause problem when you transplant the code to other languages such as c and fortran.

Reference:
“Effective C++” Third Edition by Scott Meyers.