ProgrammingHardGATE CS · TCS NQT Prime · Product Company SDE
cpp struct A { int x = 1; }; struct B : A {}; struct C : A {}; struct D : B, C {}; int main() { D d; // d.x ? } Without virtual inheritance, what is the…
struct A { int x = 1; };
struct B : A {};
struct C : A {};
struct D : B, C {};
int main() {
D d;
// d.x ?
}Without virtual inheritance, what is the problem with writing `d.x`?- A. It silently refers to B's copy of x
- B. It is a compile error because A has no user-declared constructor
- C. D automatically merges the two A subobjects into one
- D. Ambiguous: D contains two separate A subobjects (one via B, one via C), so d.x does not know which to use without qualifying it as d.B::x or d.C::x
Correct answer: D. Ambiguous: D contains two separate A subobjects (one via B, one via C), so d.x does not know which to use without qualifying it as d.B::x or d.C::x
Non-virtual inheritance gives D two independent A base subobjects, so an unqualified d.x is ambiguous and must be written d.B::x or d.C::x.
More OOP with C++ and Java questions
- 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++?
- Why can a generic method not simply write new T[10] for a type parameter T in Java?
- java void f(int x) { System.out.print("int"); } void f(Integer x) { System.out.print("Integer"); } void f(Object... x) {…