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

A union is a user-defined type where all members occupy the same overlapping memory address, with its total size equal to the size of its largest member plus alignment padding. Only one member can be actively stored at any given time. Modern C++17 provides std::variant as a type-safe, tagged union that prevents undefined behavior from reading inactive union fields.

Detailed Explanation & Mechanics

1. Union Memory Overlap:

Architecture Diagram
UNION MEMORY LAYOUT (Total size = 8 bytes):
┌─────────────────────────────────────────────────────────────┐
│ 0x00                     0x04                     0x08      │
├──────────────────────────┬──────────────────────────────────┤
│ int integerVal (4 bytes) │ (Shared)                         │
├──────────────────────────┴──────────────────────────────────┤
│ double floatVal (8 bytes)                                   │
└─────────────────────────────────────────────────────────────┘

2. C++17 `std::variant`:

A type-safe discriminated union that knows which type is currently active and throws std::bad_variant_access if accessed incorrectly.

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.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.