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;
}- A. ~Base ~Mid ~Leaf
- B. ~Leaf ~Mid ~Base
- C. ~Mid ~Leaf ~Base
- 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
- What is printed? java class Animal { Animal() { System.out.print(category() + " "); } String category() { return "Animal"; } } class Bird…
- What is printed? cpp struct Base { Base() { cout << "Base "; } Base(const Base&) { cout << "BaseCopy "; } }; struct Derived : Base {…
- What is printed? cpp int f() { std::cout << "f "; return 1; } int g() { std::cout << "g "; return 2; } int a = f(); int b = g(); int…
- What is printed? cpp struct X { int id; X(int i) : id(i) { std::cout << "X" << id << " "; } ~X() { std::cout << "~X" << id << " "; } }…
- What is printed? cpp struct Animal { void speak() { std::cout << "Animal"; } }; struct Dog : Animal { void speak() { std::cout << "Dog"; }…
- What is wrong with this generic class? java class Factory<T> { T create() { return new T(); } }