ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
struct Base { virtual void f() { cout << "B"; } };
struct D1 : Base { void f() override { cout << "1"; } };
struct D2 : Base { void f() override { cout << "2"; } };
int main() {
    Base *arr[2] = { new D1(), new D2() };
    for (auto *p : arr) p->f();
}
  1. A. BB
  2. B. 12
  3. C. B1B2
  4. D. 21

Correct answer: B. 12

Each element's actual object type is D1 or D2 respectively. Virtual dispatch through the Base* pointers looks up each object's own vtable at runtime, printing the overridden D1::f and D2::f, giving 12.

More OOP with C++ and Java questions

Exams that ask this topic