ProgrammingVery hardIBM · Deloitte pattern

What is printed (assume typical compiler codegen)?

What is printed (assume typical compiler codegen)?
struct Base { ~Base() { cout << "~Base "; } };
struct Derived : Base { int *buf = new int[4]; ~Derived() { cout << "~Derived "; delete[] buf; } };
int main() {
    Base *p = new Derived();
    delete p;
}
  1. A. ~Base
  2. B. ~Derived ~Base
  3. C. ~Base ~Derived
  4. D. Compilation error

Correct answer: A. ~Base

Base has no virtual destructor, so delete p is resolved statically: only Base::~Base runs and Derived::~Derived (and the delete[] buf inside it) never executes — a real memory leak. The standard calls this undefined behaviour, but every mainstream compiler's non-virtual codegen produces exactly this output.

More OOP with C++ and Java questions

Exams that ask this topic