ProgrammingHardGATE CS · TCS NQT Prime · Product Company SDE

cpp struct A { void f() { cout << "A::f"; } }; struct B : A {}; struct C : A {}; struct D : B, C {}; int main() { D d; d.f(); } What happens (A is inherited…

struct A { void f() { cout << "A::f"; } };
struct B : A {};
struct C : A {};
struct D : B, C {};
int main() {
    D d;
    d.f();
}
What happens (A is inherited non-virtually by both B and C)?
  1. A. Compile error: the call to f() is ambiguous, since D has two separate A subobjects, each with its own f()
  2. B. Prints "A::f" once
  3. C. Infinite recursion
  4. D. A runtime crash, but it compiles

Correct answer: A. Compile error: the call to f() is ambiguous, since D has two separate A subobjects, each with its own f()

d.f() cannot tell whether to use the A::f inherited via B or the one inherited via C, so the compiler rejects it as ambiguous.

More OOP with C++ and Java questions

Exams that ask this topic