Digital Garden
Computer Science
C++
Unions

Unions

In a union all members share the same memory location. This means that at any given time, a union can contain no more than one object from its list of members. It also means that no matter how many members a union has, it always uses only enough memory to store the largest member.

#include <iostream>
#include <string>
using namespace std;
 
union Record // will only take up a double amount in memory
{
    char   ch;
    int    i;
    long   l;
    float  f;
    double d; // biggest attribute
    int* int_ptr;
};
 
int main() {
    Record t;
    t.i = 5; // t holds an int
    t.f = 7.25; // t now holds a float, int is gone
 
    cout << t.f << endl;
    cout << t.i << endl;
}
Output