ProgrammingHardProduct-company placement · C++

What is printed?

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

Correct answer: A. ~D B

The virtual destructor runs ~D first, then ~B. By the time ~B runs, the D part is already destroyed and the object's dynamic type is B, so the virtual call hi() inside it resolves to B::hi.

More OOP with C++ and Java questions

Exams that ask this topic