ProgrammingVery hardGATE CS · TCS NQT

What does this C++ program print? struct B { virtual void f(int x = 1) { std::cout << "B" << x; } }; struct D : B { void f(int x = 2) override { std::cout << "D" << x; } }; int main() { B* p = new D; p->f(); }

  1. A. D2
  2. B. B1
  3. C. B2
  4. D. D1

Correct answer: D. D1

Which function body runs is decided at run time by the dynamic type (D::f), but default arguments are bound at compile time from the static type B*, so x = 1. The output is D1, a mix that surprises most students.

More OOP with C++ and Java questions

Exams that ask this topic