ProgrammingHardMicrosoft/Amazon SDE MCQ · GATE CS

What is printed?

What is printed?
struct B {
    virtual ~B() { hi(); }
    virtual void hi() { cout << "B"; }
};
struct D : B {
    ~D() { hi(); }
    void hi() override { cout << "D"; }
};
int main() { B* p = new D; delete p; }
  1. A. DD
  2. B. DB
  3. C. BB
  4. D. BD

Correct answer: B. DB

The virtual destructor runs ~D first, where hi() dispatches to D. By the time ~B runs the D part is gone and the dynamic type is B, so the virtual call resolves to B::hi.

More OOP with C++ and Java questions

Exams that ask this topic