ProgrammingHardTCS NQT · Cognizant GenC

What is printed? (C++, assume <iostream> and using namespace std)

What is printed? (C++, assume <iostream> and using namespace std)
struct B { virtual void f(int x = 1) { cout << "B" << x; } };
struct D : B { void f(int x = 2) override { cout << "D" << x; } };
int main() { B* p = new D; p->f(); }
  1. A. D2
  2. B. B1
  3. C. D1
  4. D. B2

Correct answer: C. D1

The virtual call picks D::f at run time, but default arguments are bound statically from the pointer type B, so x = 1.

More OOP with C++ and Java questions

Exams that ask this topic