ProgrammingVery hardProduct-company MCQ pattern

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() {
    B *p = new D;
    p->f();
}
  1. A. D1
  2. B. D2
  3. C. B1
  4. D. B2

Correct answer: A. D1

The function body is chosen at run time (D::f), but default arguments are filled in at compile time from the static type B*, so x = 1. Never give an override a different default argument.

More OOP with C++ and Java questions

Exams that ask this topic