ProgrammingVery hardGATE CS · TCS NQT Prime · Product Company SDE

A base class has a non-virtual destructor. A derived class owns a dynamically allocated member that it frees in its own destructor. What happens when `Base* p = new Derived(); delete p;` runs?

  1. A. Compile error, since p is declared as Base*
  2. B. The compiler silently makes the destructor virtual to fix it
  3. C. Both destructors run correctly regardless of virtuality
  4. D. Undefined behaviour; in practice only Base's destructor runs, so Derived's destructor (and its cleanup) is skipped, leaking the resource

Correct answer: D. Undefined behaviour; in practice only Base's destructor runs, so Derived's destructor (and its cleanup) is skipped, leaking the resource

Deleting a derived object through a base pointer with a non-virtual destructor is undefined behaviour; in practice it calls only Base's destructor, skipping Derived's cleanup.

More OOP with C++ and Java questions

Exams that ask this topic