ProgrammingVery hardProduct-company MCQ pattern
What is printed?
What is printed?
struct A { virtual void f() { cout << "A"; } };
struct B : virtual A { void f() override { cout << "B"; } };
struct C : virtual A {};
struct D : B, C {};
int main() {
D d;
A *p = &d;
p->f();
}- A. A
- B. B
- C. Compilation error: ambiguous base A
- D. AB
Correct answer: B. B
Virtual inheritance means D has exactly one shared A subobject, so there is no ambiguity. Among the two paths that could provide f(), only B actually overrides it; that override is the one visible in D's final overrider set, so dispatch through any A* to the shared subobject calls B::f.
More OOP with C++ and Java questions
- What is printed? java class Node { Node next; int val; Node(int v) { val = v; } public String toString() { return val + (next != null ?…
- What is printed? java class A { final String tag() { return "A"; } } class B extends A { String tag(int x) { return "B" + x; } } // in…
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct D1 : Base { void f() override { cout << "1"; } }; struct D2…
- 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…