ProgrammingHardProduct-company placement · GATE CS

What is printed?

What is printed?
struct B {
    B() { f(); }
    virtual ~B() { f(); }
    virtual void f() { cout << "B"; }
};
struct D : B {
    D() { f(); }
    ~D() { f(); }
    void f() override { cout << "D"; }
};
int main() { D d; }
  1. A. DDDD
  2. B. BDBD
  3. C. BDDB
  4. D. DDDB

Correct answer: C. BDDB

While B's constructor or destructor runs, the object is treated as a B, so virtual calls resolve to B::f. D's constructor and destructor see a D. Construction prints B then D; destruction runs ~D then ~B, printing D then B.

More OOP with C++ and Java questions

Exams that ask this topic