Difficulty: Easy
Correct Answer: same
Explanation:
Introduction / Context:
Unions in C++ overlay multiple members at the same memory location. Initialization and assignment rules depend on type compatibility and on whether user-declared constructors are present. This question targets the scenario where the union has no constructor and asks about the type constraints for initializing it from another union value.
Given Data / Assumptions:
Concept / Approach:
If a union has no user-declared constructors, it behaves like an aggregate for many initialization purposes. Initialization from another union is only well-formed when the source has the same union type. Different types (even layout-compatible unions) are not considered the same type. Terms like “virtual” and “class” do not describe types that satisfy this requirement; they are unrelated concepts or too broad. Therefore, the safe and correct option is “same.”
Step-by-Step Solution:
Verification / Alternative check:
Try compiling code that initializes U1 u = u2; where U1 and U2 are distinct union types with identical members; compilation fails due to mismatched types. Using exactly the same union type compiles and behaves as expected.
Why Other Options Are Wrong:
different: violates type equivalence requirements.
virtual: refers to virtual dispatch and is irrelevant for unions.
class: overly generic and not a type equality statement.
Common Pitfalls:
Final Answer:
same
Discussion & Comments