Search code examples
c++abstract-classvirtual-destructor

virtual destructor for pure abstract class


Based on what I found here and on other links on stackoverflow, we should always define a virtual destructor in the base class if we plan to use it polymorphically. I want to know if there is an exception to this rule.

I have seen production code that does not define virtual destructor for the pure abstract base classes and in one of cppcon 2014 video Accept no visitor, around 10:06 the BoolExp struct defined is a pure abstract class and has no virtual destructor.

So for a pure abstract class defined like this

  class Base {
      public:
         virtual foo() = 0;
         virtual bar() = 0;
     }

My question is it absolutely must that we define a virtual destructor for "Base" class, even though it does have any data members? Are there any exceptions to the virtual destructor rule?

Thanks in advance.

Best, RG


Solution

  • My question is it absolutely must that we define a virtual destructor for "Base" class, even though it does have any data members?

    It depends. If you have a case like

    base * foo = new child(stuff);
    // doing stuff
    delete foo;
    

    then you absolutely must have a virtual destructor. Without it you'll never destroy the child part.

    If you have a case like

    child * foo = new child(stuff);
    // doing stuff
    delete foo;
    

    Then you do not need a virtual destructor, as child's will be called.

    So the rule is if you delete polymorphically, you need a polymorphic (virtual) destructor, if not, then you don't