Search code examples
c++virtual-destructor

Virtual destructor: is it required when not dynamically allocated memory?


Do we need a virtual destructor if my classes do not allocate any memory dynamically ?

e.g.

class A
{
      private: 
      int a;
      int b;

      public:
      A();
      ~A();
};

class B: public A
{     
      private:
      int c;
      int d;

      public:
      B();
      ~B();
};

In this case do we need to mark A's destructor as virtual ?


Solution

  • The issue is not whether your classes allocate memory dynamically. It is if a user of the classes allocates a B object via an A pointer and then deletes it:

    A * a = new B;
    delete a;
    

    In this case, if there is no virtual destructor for A, the C++ Standard says that your program exhibits undefined behaviour. This is not a good thing.

    This behaviour is specified in section 5.3.5/3 of the Standard (here referring to delete):

    if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.