ProgrammingVery hardGATE CS · TCS NQT

What does this C++ program print? struct B { B() { f(); } virtual void f() { std::cout << "B"; } }; struct D : B { D() { f(); } void f() override { std::cout << "D"; } }; int main() { D d; B& r = d; r.f(); }

  1. A. BDD
  2. B. DDD
  3. C. BBD
  4. D. DBD

Correct answer: A. BDD

While B's constructor runs, the object's dynamic type is B, so the virtual call in it reaches B::f and prints B. D's constructor then calls D::f (D), and the call through the reference r dispatches virtually to D::f (D).

More OOP with C++ and Java questions

Exams that ask this topic