ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
struct M { M() { cout << "m"; } ~M() { cout << "~m"; } };
struct B {
    B() { cout << "b"; f(); }
    virtual ~B() { cout << "~b"; f(); }
    virtual void f() { cout << "B"; }
};
struct D : B {
    M m;
    D()  { cout << "d"; f(); }
    ~D() { cout << "~d"; f(); }
    void f() override { cout << "D"; }
};
int main() { B* p = new D; delete p; }
  1. A. bBmdD~dD~m~bB
  2. B. bDmdD~dD~m~bD
  3. C. mbBdD~dD~bB~m
  4. D. bBmdD~bB

Correct answer: A. bBmdD~dD~m~bB

Construction: base first, then members, then the derived body. While B's constructor runs the object is a B, so f() calls B::f. Then member m is built, then D's body prints d and calls D::f. delete through B* is safe because ~B is virtual: ~D runs (calling D::f), then members are destroyed (~m), then ~B, during which the object is a B again, so f() is B::f. Without the virtual destructor only ~B would run, which is undefined behaviour.

More OOP with C++ and Java questions

Exams that ask this topic