ProgrammingVery hardMicrosoft/Amazon SDE MCQ · GATE CS

What is printed?

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

Correct answer: D. D1D2

The function body is chosen at run time (D::f both times), but default arguments come from the static type of the expression: B& gives 1, D gives 2.

More OOP with C++ and Java questions

Exams that ask this topic