Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual destructor for pure abstract class [duplicate]

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

like image 771
DDG Avatar asked Mar 03 '23 15:03

DDG


2 Answers

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

like image 138
NathanOliver Avatar answered Mar 06 '23 06:03

NathanOliver


The exception to the rule is if you never delete an object through a pointer to the base class. In that case the base class destructor does not need to be virtual.

But if you ever delete an object via a base class pointer, then the base class destructor must be virtual or your program has Undefined Behaviour.

like image 41
Jesper Juhl Avatar answered Mar 06 '23 05:03

Jesper Juhl