Search code examples
c++virtual-destructor

Base class destructor is not virtual and child class destructor is virtual, program crash


Why does the following program crash? I have a base class whose destructor is not virtual but the child class destructor is virtual:

#include <iostream>

class Base {
public:
  Base() {
    std::cout << "Base::Base CTOR " << std::endl;
  }
  ~Base() {
    std::cout << "Base::Base DTOR " << std::endl;
  }
};

class Child : public Base {
public:
  Child(){
    std::cout << "Child::Child CTOR " << std::endl;
  }
  virtual ~Child() {
    std::cout << "Child::Child DTOR " << std::endl;
  }

};

int main (int argc, char **argv) {
  Base *ptr = new Child;
  delete ptr;
}

Solution

  • What you are observing is called "undefined behavior". Make Base's dtor virtual if you want do call delete on Child instance through Base pointer.

    From the 2003 standard, 5.3.5/3:

    In the first alternative (delete object), 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.