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();
}- A. BB
- B. 12
- C. B1B2
- 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
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct D1 : Base { void f() override { cout << "X"; } }; struct D2…
- What happens when this is compiled? java interface A { default void m() { System.out.println("A"); } } interface B { default void m() {…
- What happens when Base b; is added inside main, right before the existing lines? cpp struct Base { virtual void f() = 0; }; struct Derived…
- What happens when this is compiled? cpp struct A { int x; }; struct B : A {}; struct C : A {}; struct D : B, C {}; int main() { D d; d.x =…
- What is printed? cpp struct Base { virtual ~Base() {} }; struct Derived : Base {}; struct Other : Base {}; int main() { Base b = new…
- What is printed? java class Animal { void speak() { System.out.print(".."); } } class Dog extends Animal { void speak() {…