Topic 38 of 91 7. C++ Structures and Unions Interactive Tutorial

C++ Unions: Shared Memory Storage and Practical Examples

14 mins read Last updated: 26 Sep 2026 18,800 views

Direct Answer & Core Concept

C++ provides several user-defined data types that help organize information. Structures (struct) group multiple data members together, while unions (union) allow multiple members to share the same memory location.

Unions are useful when a program needs to store one value from several possible data types at a time.

For example, an application might need to store:

  • An integer value.

  • A floating-point value.

  • A character.

  • A Boolean value.

Instead of allocating separate storage for every member, a union provides shared storage for its members.

Detailed Explanation & Mechanics

1. What Is a Union in C++?

A union is a user-defined data type in C++ in which all non-static data members share the same memory location.

Unlike a structure, where each member has its own storage, union members overlap in memory.

This means that a union is generally used to hold one active member at a time.

Syntax of a Union

main.cpp
Run Online
union UnionName {
    data_type member1;
    data_type member2;
    data_type member3;
};

Here:

  • union is the keyword used to define a union.

  • UnionName is the name of the union.

  • member1, member2, and member3 are its data members.

  • The semicolon after the closing brace is required.

Example: Declare a Union

main.cpp
Run Online
#include <iostream>
using namespace std;

union Data {
    int number;
    float decimal;
    char letter;
};

int main() {
    return 0;
}

The Data union contains three members:

MemberData typePurpose
numberintStores an integer
decimalfloatStores a decimal value
lettercharStores a character

All three members share the same storage.

2. How Does a Union Work in C++?

The main feature of a union is shared memory.

Consider this union:

main.cpp
Run Online
union Data {
    int number;
    float decimal;
    char letter;
};

The compiler allocates enough storage to accommodate its largest member, subject to the type's alignment requirements.

For example, if an implementation uses:

  • int requiring 4 bytes,

  • float requiring 4 bytes,

  • char requiring 1 byte,

the union will typically require 4 bytes, although its exact size depends on the implementation and alignment.

<AsyncImage query="C++ union shared memory educational diagram overlapping int float char members same memory block labeled union memory layout simple programming infographic" aspectRatio="16:9" width="100%" maxHeight={220}/>

Important: The members do not have separate independent values. Writing to one member changes the shared storage and generally ends the lifetime of the previously active member.

3. Declaring and Creating Union Variables

After defining a union, you can create variables using its name.

Syntax

Example:

main.cpp
Run Online
union Data {
    int number;
    float decimal;
    char letter;
};

int main() {
    Data value;

    return 0;
}

Here, value is a union object.

You can also create multiple union variables:

main.cpp
Run Online
Data first;
Data second;
Data third;

Each union object has its own shared storage.

4. Accessing Union Members

The dot (.) operator is used to access union members through an object.

Example: Store and Display an Integer

main.cpp
Run Online
#include <iostream>
using namespace std;

union Data {
    int number;
    float decimal;
    char letter;
};

int main() {
    Data value;

    value.number = 100;

    cout << "Number: " << value.number;

    return 0;
}

Output:

The program stores an integer in the union and reads that same active member.

5. Understanding Shared Memory With an Example

When you assign a value to one union member, that member becomes active.

Consider this example:

main.cpp
Run Online
#include <iostream>
using namespace std;

union Data {
    int number;
    float decimal;
    char letter;
};

int main() {
    Data value;

    value.number = 100;

    cout << "Integer: " << value.number << endl;

    value.decimal = 25.5f;

    cout << "Float: " << value.decimal << endl;

    return 0;
}

Output:

Explanation:

  1. value.number = 100 activates the integer member.

  2. The program reads and displays the integer.

  3. value.decimal = 25.5f activates the floating-point member.

  4. The previous integer member is no longer the active member.

  5. The program reads and displays the floating-point value.

The example does not read the inactive integer member after assigning the float.

Important: Do not assume that assigning one union member allows you to read another member as though it still contains its original value. Reading an inactive member is generally not permitted, apart from specific language rules such as inspecting the common initial sequence of standard-layout struct members in an appropriate union.

6. Initializing a Union in C++

You can initialize a union when declaring its variable.

Example 1: Initialize the First Member

main.cpp
Run Online
#include <iostream>
using namespace std;

union Data {
    int number;
    float decimal;
    char letter;
};

int main() {
    Data value = {100};

    cout << value.number;

    return 0;
}

Output:

Traditional aggregate initialization without a designated member initializes the first member.

Example 2: Initialize a Specific Member Using a Designated Initializer

C++20 supports designated initializers for aggregates.

main.cpp
Run Online
#include <iostream>
using namespace std;

union Data {
    int number;
    float decimal;
    char letter;
};

int main() {
    Data value = {.decimal = 25.5f};

    cout << value.decimal;

    return 0;
}

Output:

The designated initializer identifies which member should be initialized.

7. Updating Union Members

You can change the active member by assigning a value to another member.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

union Data {
    int number;
    float decimal;
    char letter;
};

int main() {
    Data value;

    value.letter = 'A';
    cout << "Character: " << value.letter << endl;

    value.number = 500;
    cout << "Integer: " << value.number << endl;

    value.decimal = 12.5f;
    cout << "Float: " << value.decimal << endl;

    return 0;
}

Output:

main.cpp
Run Online
Character: A
Integer: 500
Float: 12.5

Each assignment activates a different member. Only the currently active member is read.

8. Finding the Size of a Union

The sizeof operator returns the size of a union object in bytes.

The size is sufficient to hold its largest member, taking alignment and implementation requirements into account.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

union Data {
    int number;
    double decimal;
    char letter;
};

int main() {
    cout << "Size of int: " << sizeof(int) << endl;
    cout << "Size of double: " << sizeof(double) << endl;
    cout << "Size of char: " << sizeof(char) << endl;

    cout << "Size of union: " << sizeof(Data) << endl;

    return 0;
}

Example output on a common platform:

main.cpp
Run Online
Size of int: 4
Size of double: 8
Size of char: 1
Size of union: 8

The exact output depends on the platform and compiler.

The union size is not necessarily the simple sum of its member sizes. It is generally at least as large as its largest member and must also satisfy alignment requirements.

9. Array of Unions in C++

You can create an array of union objects just as you can create an array of structures.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

union Data {
    int number;
    float decimal;
};

int main() {
    Data values[3];

    values[0].number = 10;
    values[1].decimal = 20.5f;
    values[2].number = 30;

    cout << values[0].number << endl;
    cout << values[1].decimal << endl;
    cout << values[2].number << endl;

    return 0;
}

Output:

Each element in the array is a separate union object with its own shared storage.

10. Pointers to Unions

You can create a pointer that stores the address of a union object.

Use the arrow (->) operator to access members through the pointer.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

union Data {
    int number;
    float decimal;
};

int main() {
    Data value;

    Data* ptr = &value;

    ptr->number = 100;

    cout << "Number: " << ptr->number;

    return 0;
}

Output:

Here:

  • ptr stores the address of the union object.

  • ptr->number accesses the integer member.

  • The integer member becomes active when assigned.

The arrow operator is equivalent to dereferencing the pointer and using the dot operator:

11. Passing a Union to a Function

Like structures, unions can be passed to functions by value, by reference, or by constant reference.

Example: Pass a Union by Value

main.cpp
Run Online
#include <iostream>
using namespace std;

union Data {
    int number;
    float decimal;
};

void display(Data value) {
    cout << "Number: " << value.number << endl;
}

int main() {
    Data data;

    data.number = 100;

    display(data);

    return 0;
}

Output:

The function receives a copy of the union object. In this example, the integer member is active in the copied object.

Example: Pass a Union by Reference

main.cpp
Run Online
#include <iostream>
using namespace std;

union Data {
    int number;
    float decimal;
};

void update(Data& value) {
    value.number = 500;
}

int main() {
    Data data;

    data.number = 100;

    update(data);

    cout << data.number;

    return 0;
}

Output:

Passing by reference allows the function to update the original union object.

12. Union With a Structure in C++

A union can be used as a member of a structure. This is useful when a record can contain one of several possible value types.

However, the program should also store information identifying which union member is active.

This is commonly called a tagged union or discriminated union.

Example: Structure With a Union Member

main.cpp
Run Online
#include <iostream>
using namespace std;

struct Value {
    int type;

    union {
        int integerValue;
        float floatValue;
        char characterValue;
    } data;
};

int main() {
    Value value;

    value.type = 1;
    value.data.integerValue = 100;

    if (value.type == 1) {
        cout << "Integer: " << value.data.integerValue;
    }

    return 0;
}

Output:

Explanation:

  • type identifies the active value type.

  • data stores the selected value in shared memory.

  • The program checks type before reading the corresponding union member.

The programmer must keep the tag and active union member consistent.

For many applications, std::variant is a safer alternative because it tracks the currently held type automatically.

13. Difference Between Structure and Union in C++

Structures and unions are both user-defined data types, but their memory organization is different.

FeatureStructure (struct)Union (union)
Memory allocationSeparate storage for each non-static memberMembers share storage
Member valuesAll members can hold independent valuesNormally one active member at a time
SizeIncludes storage for all members and paddingSufficient for the largest member and alignment
AccessDot or arrow operatorDot or arrow operator
Use caseGrouping related dataAlternative values sharing storage
Member initializationSupports multiple membersInitializes an active member

Example: Structure

main.cpp
Run Online
struct Data {
    int number;
    float decimal;
    char letter;
};

All three members can hold independent values at the same time.

Example: Union

main.cpp
Run Online
union Data {
    int number;
    float decimal;
    char letter;
};

The members share storage, so the union is generally used for one active value at a time.

14. Union vs std::variant in Modern C++

C++17 introduced std::variant, which provides a type-safe way to store one value from a list of alternative types.

Unlike a raw union, std::variant tracks which alternative is currently active and manages the lifetime of its contained value.

Example: Using std::variant

main.cpp
Run Online
#include <iostream>
#include <variant>
using namespace std;

int main() {
    variant<int, float, string> value;

    value = 100;
    cout << get<int>(value) << endl;

    value = 25.5f;
    cout << get<float>(value) << endl;

    value = string("Hello C++");
    cout << get<string>(value) << endl;

    return 0;
}

Output:

std::variant is often a better choice when you need a value that can hold one of several different types safely.

FeatureUnionstd::variant
IntroducedAvailable in C++C++17
Shared storageYesUses storage for its alternatives
Tracks active typeNot automaticallyYes
Type safetyRequires careful managementType-safe access
Complex member typesRequires careful lifetime managementSupports suitable non-trivial types
Typical useLow-level storage and specialized layoutsType-safe alternative values

15. Real-World Applications of Unions in C++

Unions can be useful in applications where memory layout and alternative data representations matter.

Embedded Systems

Embedded applications may use unions to represent different interpretations of data while working with constrained memory.

Hardware and Device Programming

Low-level code may use unions when interacting with hardware representations, provided the implementation and hardware requirements are properly understood.

Network Protocols

A data field may represent different types of information depending on a message type or protocol tag.

Compilers and Interpreters

A value representation may need to store one of several possible data types.

Memory-Constrained Applications

Unions can reduce storage requirements when only one of several alternative values needs to be active at a time.

Note: Unions do not automatically make a program faster. Choose them when their shared-storage behavior is genuinely useful.

16. Common Mistakes When Using Unions

Mistake 1: Reading an Inactive Member

Incorrect:

main.cpp
Run Online
union Data {
    int number;
    float decimal;
};

int main() {
    Data value;

    value.number = 100;

    cout << value.decimal; // Generally not valid
}

The integer member is active. Reading the floating-point member this way is not generally permitted by the C++ object-lifetime rules.

Read the active member instead.

Mistake 2: Assuming All Members Have Separate Values

main.cpp
Run Online
union Data {
    int number;
    float decimal;
};

You should not treat number and decimal as independent storage locations. They overlap.

Mistake 3: Forgetting to Track the Active Member

When a union is used inside a larger structure, the program should keep track of which member is active.

Without that information, code may accidentally read the wrong member.

Mistake 4: Ignoring Member Lifetime Rules

Unions containing types with non-trivial constructors or destructors require careful lifetime management.

For complex alternative types, consider std::variant instead.

Mistake 5: Assuming the Union Size Is the Sum of Its Members

A union does not normally allocate separate storage for every member. Its size is based on its largest member and alignment requirements, not the sum of all member sizes.

17. Best Practices for Using Unions

  1. Use unions only when shared storage is genuinely required.

  2. Keep track of the currently active member.

  3. Never read an inactive member unless a specific C++ language rule permits it.

  4. Use std::variant when you need type-safe alternative values.

  5. Be careful with unions containing complex types such as std::string.

  6. Understand object lifetime and construction rules before using non-trivial union members.

  7. Avoid relying on platform-specific memory layouts unless the application requires them.

  8. Test low-level union code with the intended compiler and target platform.

  9. Document which member is active and how that state is maintained.

  10. Prefer simpler structures or standard library types when shared storage is unnecessary.

18. Frequently Asked Questions (FAQs)

1. What is a union in C++?

A union is a user-defined data type in which all non-static data members share the same memory location.

2. Which keyword is used to create a union?

The union keyword is used to declare a union in C++.

3. How is a union different from a structure?

A structure provides separate storage for its non-static data members, while union members share storage.

4. Can a union contain different data types?

Yes. A union can contain members with different data types, such as int, float, char, and other suitable types.

5. Can all union members store independent values at the same time?

No. A union normally has one active member at a time because its members share the same storage.

6. How do you access union members?

Use the dot (.) operator with a union object or the arrow (->) operator with a pointer.

7. How do you find the size of a union?

Use the sizeof operator:

The result depends on the largest member and the alignment requirements.

8. Can we create an array of unions?

Yes. You can declare an array of union objects:

Each element has its own union storage.

9. Can a union contain a structure?

Yes. A union can contain a structure as one of its members, subject to the normal member lifetime rules.

10. Can we pass a union to a function?

Yes. You can pass a union by value, by reference, or by constant reference.

11. Can a union contain a string in C++?

Yes, but a std::string is a non-trivial type. Managing its construction, destruction, and active-member lifetime inside a union requires care. std::variant is often a safer option.

12. What is std::variant?

std::variant is a C++17 standard library type that stores one value from several alternative types and tracks which type is currently active.

Runnable Code Example: C++ Unions

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <variant>
#include <string>

// Type-safe Modern C++17 Variant
using ConfigValue = std::variant<int, double, std::string>;

int main() {
    ConfigValue setting = 404; // Holds int
    std::cout << "Integer value: " << std::get<int>(setting) << "
";

    setting = std::string("https://operatetools.com/api"); // Holds string
    std::cout << "String value:  " << std::get<std::string>(setting) << "
";

    // Pattern matching with std::visit
    std::visit([](const auto& val) {
        std::cout << "Visited active value: " << val << "
";
    }, setting);

    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What happens if you read a union member that was not the last one written?

A: In C++, accessing a union member other than the active member is undefined behavior (type punning), except for standard-layout unions with common initial sequences.
Q

Q: Why is std::variant preferred over raw unions in modern C++?

A: `std::variant` automatically tracks the active type index, handles non-trivial constructors/destructors safely, and prevents memory corruption by throwing exceptions on invalid type access.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Prefer `std::variant` (C++17) over raw `union` for type-safe polymorphic data holding. 2. Use raw unions only for low-level hardware registers, binary protocol decoding, or micro-optimizations. 3. Use `std::holds_alternative(variant)` or `std::visit` to inspect variant data safely.