ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
struct Base { virtual ~Base() { cout << "~Base "; } };
struct Mid : Base { ~Mid() { cout << "~Mid "; } };
struct Leaf : Mid { ~Leaf() { cout << "~Leaf "; } };
int main() {
    Base *p = new Leaf();
    delete p;
}
  1. A. ~Base ~Mid ~Leaf
  2. B. ~Leaf ~Mid ~Base
  3. C. ~Mid ~Leaf ~Base
  4. D. Undefined behaviour: Mid has no virtual destructor declared

Correct answer: B. ~Leaf ~Mid ~Base

Once a base class declares a virtual destructor, every derived class's destructor is implicitly virtual too, even without repeating the keyword. delete p correctly starts destruction at the most-derived class, Leaf, then proceeds up the hierarchy: ~Leaf, then ~Mid, then ~Base.

More OOP with C++ and Java questions

Exams that ask this topic