ProgrammingHardProduct-company MCQ pattern
What happens when this is compiled?
What happens when this is compiled?
struct A { int x; };
struct B : A {};
struct C : A {};
struct D : B, C {};
int main() {
D d;
d.x = 5;
}- A. Compiles; d.x refers to the single shared A::x
- B. Compile-time error: d.x is ambiguous, because D has two separate A subobjects (via B and via C)
- C. Compiles; d.x refers to B::x by default since B is listed first
- D. Runtime error: ambiguous member access
Correct answer: B. Compile-time error: d.x is ambiguous, because D has two separate A subobjects (via B and via C)
Without virtual inheritance, D contains two independent A subobjects, one inherited through B and one through C, each with its own x. Writing d.x does not say which one is meant, so the compiler rejects it as ambiguous; it would need d.B::x or d.C::x.
More OOP with C++ and Java questions
- 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]…
- What is printed? cpp struct Vehicle { virtual string type() { return "Vehicle"; } }; struct Car : Vehicle { string type() override {…
- What is printed? java abstract class Shape { abstract double area(); String describe() { return "Area=" + area(); } } class Square extends…
- What is printed? java class Base { protected String name() { return "Base"; } public String greet() { return "Hi " + name(); } } class…