Recall & Review
beginner
What is a union in C++?
A union is a special data type where all members share the same memory location. Only one member can hold a value at a time.
Click to reveal answer
beginner
How does memory allocation work in a union?
The size of a union is equal to the size of its largest member because all members share the same memory space.
Click to reveal answer
beginner
Can you store values in multiple members of a union at the same time?
No, only one member can store a value at a time. Writing to one member overwrites the others.
Click to reveal answer
beginner
How do you access members of a union?
You access union members using the dot (.) operator if you have a union variable, or arrow (->) if you have a pointer to a union.
Click to reveal answer
intermediate
Why would you use a union instead of a struct?
Unions save memory when you need to store different types but only one at a time, unlike structs which allocate memory for all members.
Click to reveal answer
What happens when you assign a value to one member of a union?
✗ Incorrect
In a union, all members share the same memory, so assigning a value to one member overwrites the others.
What determines the size of a union?
✗ Incorrect
The union's size equals the size of its largest member because all members share the same memory.
Which operator is used to access a member of a union variable?
✗ Incorrect
The dot operator is used to access members of a union variable directly.
Why might you choose a union over a struct?
✗ Incorrect
Unions save memory by sharing space among members, useful when only one member is needed at a time.
What will happen if you read a union member different from the one last written?
✗ Incorrect
Reading a different member than the one last written can produce unpredictable results because the memory is shared.
Explain what a union is and how it manages memory.
Think about how a single box can hold different items but only one at a time.
You got /3 concepts.
Describe a situation where using a union is better than using a struct.
Imagine you have a tool that can be a hammer or a screwdriver, but you only use one function at a time.
You got /3 concepts.