ProgrammingModerateTCS NQT · HCL
In C++, a Base pointer holds a Derived object created with new, and the Base destructor is NOT virtual. What happens on delete basePtr?
- A. The Derived destructor runs first, then the Base destructor, always
- B. Only the Base destructor runs, and this is guaranteed to be safe
- C. A compile-time error is reported
- D. Undefined behaviour; the Derived destructor is not guaranteed to run
Correct answer: D. Undefined behaviour; the Derived destructor is not guaranteed to run
Deleting a derived object through a base pointer without a virtual destructor is undefined behaviour, commonly causing leaks of the derived part.
More OOP with C++ and Java questions
- What is printed? java static void f(int x) { System.out.print("int"); } static void f(long x) { System.out.print("long"); } static void…
- What happens when this C++ program is compiled? cpp struct B { int x = 5; }; class D : B { }; int main() { D d; cout << d.x; }
- What is printed? java static int f() { try { return 1; } finally { System.out.print("F"); } } public static void main(String[] a) {…
- In Java, an interface declares int MAX = 10;. What happens if an implementing class executes MAX = 20; ?
- What is printed? (C++, assume <iostream> and using namespace std) cpp struct A { A() { cout << "c"; } A(const A&) { cout << "k"; } ~A() {…
- What is printed? java class P { static String w() { return "P"; } } class Q extends P { static String w() { return "Q"; } } // in main: P…