Unions
Classes and structs store data members in separate chunks of memory, while union types only allocate enough memory to store the largest data member. All members of a union share the same memory location; consequently, one chunk of allocated memory can be used to access different data types if they were to be laid out the same in memory. Unions are a data type that you don't see a lot of, but it is worth having some understanding of how they work. One useful advantage is being able to read data in one format and then access it in another.
The following example shows a union type called Backpack
. This has an array of four integers and a struct named data
that has four int
members. Look closely at how the data can be set and read using both the array and the struct:
Example08_1.cpp
1 #include <iostream> 2 3 using namespace std; 4 5 union Backpack 6 { 7 ...