ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
struct A { virtual void f() { cout << "A"; } };
struct B : A { void f() override { cout << "B"; A::f(); } };
int main() {
    A *p = new B();
    p->f();
}
  1. A. B
  2. B. A
  3. C. BA
  4. D. AB

Correct answer: C. BA

p->f() dispatches virtually to B::f(), which first prints B, then explicitly calls A::f() by name (a statically bound call that bypasses virtual dispatch), printing A. Result: BA.

More OOP with C++ and Java questions

Exams that ask this topic