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)?- A. Compile error: the call to f() is ambiguous, since D has two separate A subobjects, each with its own f()
- B. Prints "A::f" once
- C. Infinite recursion
- 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
- Why can a private method in a Java superclass never be overridden by a subclass, only unintentionally hidden (i.e. always statically bound)?
- cpp struct A { int x = 1; }; struct B : A {}; struct C : A {}; struct D : B, C {}; int main() { D d; // d.x ? } Without virtual…
- Why did Java and C# choose single inheritance of classes plus multiple inheritance of interfaces, instead of C++-style full multiple…
- Which statement correctly distinguishes an abstract class from an interface in Java (interfaces may have default/static/private methods…
- Within a single derived class's own constructor body, in what order are its direct base class subobjects (assuming no virtual inheritance)…
- Which statement correctly describes the typical cost of exceptions in C++?