C++ virtual destructors and RAII

Virtual destructoren in C++ base classes are essential if polymorphism is used. This is a working example, note the usage of polymorphism in the main() function:

#include <iostream>
 
/*
 * RAIITest Class models RAII behavior that depends on destructor being called when object goes out of scope.
 */
class RAIITest {
public:
    RAIITest() {
        std::cout << "-RAII- constructor" << std::endl;
    }
    ~RAIITest() {
        std::cout << "-RAII- destructor" << std::endl;
    }
};
 
/*
 * Base has a virtual destructor
 */
class Base {
public:
    Base() {
        std::cout << "-Base- constructor" << std::endl;
    }
    virtual ~Base() {
        std::cout << "-Base- destructor" << std::endl;
    }
};
 
/*
 * Derived has a RAII class with a destructor defined
 */
class Derived : public Base {
public:
    RAIITest test;
   
    Derived() {
        std::cout << "-Derived- constructor" << std::endl;  
    }
    virtual ~Derived()
    {
        std::cout << "-Derived- destructor" << std::endl;
    }
};
 
int main()
{
    Base *b = new Derived();
    // use b
    delete b;
}

Output:

-Base- constructor
-RAII- constructor
-Derived- constructor
-Derived- destructor
-RAII- destructor
-Base- destructor

If the destructor of the Base class were not virtual, neither the destructor of Derived nor the destructor of RAIITest would be called. This is a common pitfall when using C++ polymorphism.

You can experiment using this Coliru Online Compiler Link and change the definition of the Base class destructor and see how it affects the Derived and RAIITest destructor calls (they will not be called).

Resources:

http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors/461224#461224

http://www.gotw.ca/publications/mill18.htm

https://isocpp.org/wiki/faq/virtual-functions#overview-virtual-fns