ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
struct Base { virtual void f() { cout << "B"; } };
struct D1 : Base { void f() override { cout << "X"; } };
struct D2 : Base { void f() override { cout << "Y"; } };
struct D3 : Base { };
int main() {
    Base *arr[3] = { new D1(), new D2(), new D3() };
    for (auto *p : arr) p->f();
}
  1. A. XYB
  2. B. BBB
  3. C. XYZ
  4. D. Compile-time error: D3 does not override f

Correct answer: A. XYB

D1 and D2 override f, printing X and Y for their objects. D3 does not override f at all, so it inherits Base::f unchanged, printing B. Result: XYB.

More OOP with C++ and Java questions

Exams that ask this topic