ProgrammingHardAccenture · Cognizant pattern
In C++, Base has a non-virtual destructor and Derived : public Base owns a heap buffer freed in ~Derived. What happens on: Base *p = new Derived; delete p; ?
- A. Compilation error
- B. Only ~Derived runs
- C. Undefined behaviour; in practice ~Derived is skipped and the buffer leaks
- D. Both destructors run, Derived first
Correct answer: C. Undefined behaviour; in practice ~Derived is skipped and the buffer leaks
Deleting a derived object through a base pointer whose destructor is not virtual is undefined; typically only ~Base runs, so the derived part is never cleaned up. Any class meant to be a polymorphic base needs a virtual destructor.
More OOP with C++ and Java questions
- What is printed? java String a = "hi"; String b = "hi"; String c = new String("hi"); System.out.print((a == b) + " " + (a == c) + " " +…
- What is printed? java System.out.print('a' + 1); System.out.print(" "); System.out.print("" + 'a' + 1);
- What is printed? cpp void f(int) { cout << "int "; } void f(double) { cout << "double "; } int main() { f('a'); f(2.5f); }
- What is printed? cpp struct A { A() { cout << "C"; } A(const A &) { cout << "K"; } ~A() { cout << "D"; } }; void f(A a) { } int main() { A…
- What is printed? cpp class A { public: static int count; A() { count++; } ~A() { count--; } }; int A::count = 0; int main() { A a, b; { A…
- Which line fails to compile? cpp struct Shape { virtual double area() = 0; }; struct Circle : Shape { }; struct Square : Shape { double…