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;
}- A. ~Base
- B. ~Derived ~Base
- C. ~Base ~Derived
- 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
- What happens when this line is compiled? java List<String>[] arr = new List<String>[10];
- What is printed? java class A { static void who() { System.out.print("A"); } } class B extends A { static void who() {…
- What is printed? java class K { int a, b; K(int a, int b) { this.a = a; this.b = b; } public int hashCode() { return 1; } public boolean…
- What is printed? java class Counter { private int count = 0; void inc() { count++; } int get() { return count; } } class LoggingCounter…
- What is printed? java String a = "hel" + "lo"; String b = "hello"; System.out.println(a == b);
- Which statement about this code is correct? java class P { P(int x) { System.out.print("P" + x + " "); } } class C extends P { C() {…