C++ unions: a union without any user-declared constructor can be initialized from another union of which type?

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:

  • No user-defined constructors exist in the union.
  • Initialization is performed using another union as a source value.
  • We focus on type compatibility in standard C++.


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:

Confirm that constructors are absent → aggregate-like behavior. Check type of source union → must be exactly the same union type. Attempt cross-type initialization → ill-formed. Conclude: initialization permitted only from the same union type.


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:

  • Assuming layout or member similarity implies type compatibility—it does not.
  • Overlooking that user-defined constructors change initialization rules entirely.


Final Answer:

same

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion