ProgrammingHardGATE CS · TCS Digital · Advanced

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

What is printed? (C++17, 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();
    D d;
    d.f();
}
  1. A. B1D2
  2. B. D2D2
  3. C. D1D2
  4. D. D1D1

Correct answer: C. D1D2

The virtual call dispatches on the dynamic type (D::f runs), but default arguments are bound at compile time from the static type: through B* the default is 1, through D the default is 2.

More OOP with C++ and Java questions

Exams that ask this topic