ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct A { virtual void f() { cout << "A"; } };
struct B : A { void f() override { cout << "B"; } };
struct C : B { void f() override { cout << "C"; } };
int main() {
    A a; B b; C c;
    A *arr[3] = { &a, &b, &c };
    for (auto *p : arr) p->f();
}
  1. A. AAA
  2. B. ABC
  3. C. CCC
  4. D. Compile-time error: cannot mix A, B, C objects in an A* array

Correct answer: B. ABC

A*[3] can hold pointers to A or any derived type; each pointer's real pointee determines the virtual dispatch, independent of the other elements. &a is a plain A, printing A; &b is a B, printing B (its own override); &c is a C, printing C. Result: ABC.

More OOP with C++ and Java questions

Exams that ask this topic