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?
- A. Compile error, since p is declared as Base*
- B. The compiler silently makes the destructor virtual to fix it
- C. Both destructors run correctly regardless of virtuality
- 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
- java interface Greet { default String hello() { return "Hi"; } } class English implements Greet {} class French implements Greet { public…
- Why is operator<< for printing a user-defined type usually written as a free function (often declared a friend), rather than as a member…
- java class R implements AutoCloseable { public void close() { System.out.print("close"); } } try (R r = new R()) {…
- Which statement about C++ vtables is correct for a class with multiple virtual functions?
- Class A's constructor declares throws IOException. Class B extends A. What must every constructor of B do about this checked exception?
- What access modifier and finality does a field declared directly inside a Java interface implicitly have?