ProgrammingVery hardProduct company OA

What is printed?

What is printed?
struct A { virtual void f(int x) { std::cout << "A::f(int) " << x; } };
struct B : A { virtual void f(double x) { std::cout << "B::f(double) " << x; } };
int main() {
    B b;
    A *p = &b;
    p->f(5);
}
  1. A. B::f(double) 5
  2. B. A::f(int) 5
  3. C. Compilation error: ambiguous call
  4. D. A::f(int) 5B::f(double) 5

Correct answer: B. A::f(int) 5

B::f(double) is a DIFFERENT signature from A::f(int), so it does not override A::f(int) — it's a separate virtual function. Since p's static type is A*, only A's member list (which has f(int)) is visible for overload resolution, and it IS virtual, so it dispatches based on A's vtable entry for f(int), which b inherits unchanged. Prints A::f(int) 5.

More OOP with C++ and Java questions

Exams that ask this topic