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();
}- A. XYB
- B. BBB
- C. XYZ
- 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
- 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() {…
- What is printed? cpp struct Base { public: virtual ~Base() { cout << "~Base "; } }; struct Derived : Base { int data = new int[10]…