0
0
C++programming~5 mins

Union basics in C++ - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AIt stores values in all members simultaneously.
BIt creates a copy of the value in each member.
CIt overwrites the value of other members.
DIt causes a compilation error.
What determines the size of a union?
AThe size of its largest member.
BThe sum of sizes of all members.
CThe size of the first member.
DAlways 4 bytes.
Which operator is used to access a member of a union variable?
A& (ampersand)
B. (dot)
C* (asterisk)
D-> (arrow)
Why might you choose a union over a struct?
ATo enforce type safety.
BTo store multiple values simultaneously.
CTo create a class.
DTo save memory when only one member is used at a time.
What will happen if you read a union member different from the one last written?
AYou may get unexpected or garbage data.
BYou get the last written value correctly.
CIt causes a runtime error.
DIt automatically converts the value.
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.