C++ Unions – Efficient Memory Sharing with One Value at a Time
Introduction – Why Learn C++ Unions?
In C++ programming, a union is a special data structure that allows multiple variables to occupy the same memory location. Only one member can hold a value at any given time. Unions are primarily used when memory optimization is critical — such as in embedded systems or low-level programming.
In this guide, you’ll learn:
- What a union is and how it works
- Syntax and usage of unions
- How unions differ from structures
- Use cases and performance benefits
- Common pitfalls and best practices
Core Concept – What is a Union in C++?
A union is similar to a struct, but all members share the same memory. Assigning a new value to one member overwrites the others.
union Data {
int i;
float f;
char c;
};
Here, all three members share the same memory location. You can store only one of them at a time.
Code Examples – With Step-by-Step Explanations
Example 1: Basic Union Usage
#include <iostream>
using namespace std;
union Data {
int i;
float f;
};
int main() {
Data d;
d.i = 10;
cout << "Integer: " << d.i << endl;
d.f = 3.14f; // Overwrites 'i'
cout << "Float: " << d.f << endl;
cout << "Integer (now invalid): " << d.i << endl;
return 0;
}
Output:
Integer: 10
Float: 3.14
Integer (now invalid): <garbage>
Explanation:
- After assigning
f, the value ofiis lost or becomes undefined.
Example 2: Union Size and Memory Layout
#include <iostream>
using namespace std;
union Value {
int i;
double d;
char c;
};
int main() {
cout << "Size of union: " << sizeof(Value) << " bytes\n";
return 0;
}
Output:Size of union: 8 bytes (on most 64-bit systems)
Why?
The union size equals the size of its largest member (here, double = 8 bytes).
Example 3: Anonymous Union in struct
#include <iostream>
using namespace std;
struct Record {
int type; // 1 = int, 2 = float
union {
int i;
float f;
};
};
int main() {
Record r;
r.type = 1;
r.i = 99;
if (r.type == 1)
cout << "Integer: " << r.i << endl;
else
cout << "Float: " << r.f << endl;
return 0;
}
Anonymous unions allow direct access to union members without a variable name.
Best Practices & Tips
Best Practices:
- Use unions when memory savings are critical
- Document union usage clearly to avoid misuse
- Prefer
std::variant(C++17) for type-safe alternatives
Tips:
- Use an external
typefield to track which member is active - Always access the member you most recently assigned
Pitfalls:
- Accessing inactive member ➝ Undefined Behavior
- Confusing unions with
struct➝ wrong expectations - Cannot contain non-trivial constructors (pre-C++11)
Comparison Table – Union vs Structure
| Feature | struct | union |
|---|---|---|
| Memory layout | Members have separate memory | Members share same memory |
| Size | Sum of all members | Size of largest member |
| Active members | All can hold values | Only one member at a time |
| Use case | Group multiple fields | Optimize memory for one-at-a-time fields |
| Trivial members | Supports all | Limited support (no non-trivial members pre-C++11) |
Use Cases & Performance Notes
Use Cases:
- Low-level device drivers
- Embedded systems
- Protocol headers
- Tagged union design pattern (with type field)
Performance Notes:
- Reduces memory footprint significantly
- Avoids dynamic memory allocation
- Error-prone without proper active member tracking
Summary – Recap & Next Steps
C++ unions are powerful tools for optimizing memory when multiple variables are mutually exclusive in use. They are essential in systems-level programming and can be used effectively when handled with care.
Key Takeaways:
- Union stores one value at a time, all members share memory
- Size is determined by the largest member
- Use
typetracking to manage safely
Next Steps:
- Explore
std::variantfor modern, type-safe alternatives - Combine unions with
enumto build tagged unions - Learn about C++ Structures and
classfor grouped data
FAQ Section
What is the main purpose of a union in C++?
To save memory by storing only one value at a time in the same location.
Can a union contain functions?
Yes, but only static functions or friend functions. Member functions are not typical.
What happens if I access a member that wasn’t last assigned?
It results in undefined behavior. Use tracking fields to avoid this.
Are unions type-safe in C++?
No, traditional unions are not. For type-safe behavior, use std::variant (C++17).
Can unions be inherited in C++?
Technically yes, but inheritance with unions is rarely practical or recommended.
Share Now :
