ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
struct A {
    virtual void f() { std::cout << "A::f "; }
};
struct B : A {
    void f() override { std::cout << "B::f "; }
    void f(int x) { std::cout << "B::f(int) " << x; }
};
int main() {
    B b;
    A &ra = b;
    ra.f();
}
  1. A. Compilation error: ambiguous between f() and f(int)
  2. B. B::f(int) 0
  3. C. A::f
  4. D. B::f

Correct answer: D. B::f

Through ra (static type A&), only A's interface is visible for overload resolution, which has exactly one f() taking no arguments. That resolves to the f() slot, and virtual dispatch sends it to B's override at runtime: B::f.

More OOP with C++ and Java questions

Exams that ask this topic