๐งฌ 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 :
