0Pricing
C++ Academy · Lesson

Unions and Their Risks

Share memory between types.

What Is a Union?

A union lets several members share the same memory. Only one member is valid at a time, and the union is only as big as its largest member.

#include <iostream>
union Number {
    int i;
    float f;
};
int main() {
    Number n;
    n.i = 42;
    std::cout << n.i << "\n";
}

Size of a Union

Because members overlap, sizeof a union equals the size of its largest member (plus any alignment padding), not the sum.

#include <iostream>
union Mix { char c; int i; double d; };
int main() {
    std::cout << sizeof(Mix) << "\n"; // size of double (often 8)
}

All lessons in this course

  1. Scoped enum class
  2. Unions and Their Risks
  3. std::variant
  4. std::visit
← Back to C++ Academy