ProgrammingHardAccenture · Cognizant pattern

In C++, Base has a non-virtual destructor and Derived : public Base owns a heap buffer freed in ~Derived. What happens on: Base *p = new Derived; delete p; ?

  1. A. Compilation error
  2. B. Only ~Derived runs
  3. C. Undefined behaviour; in practice ~Derived is skipped and the buffer leaks
  4. D. Both destructors run, Derived first

Correct answer: C. Undefined behaviour; in practice ~Derived is skipped and the buffer leaks

Deleting a derived object through a base pointer whose destructor is not virtual is undefined; typically only ~Base runs, so the derived part is never cleaned up. Any class meant to be a polymorphic base needs a virtual destructor.

More OOP with C++ and Java questions

Exams that ask this topic