union
TypeThe name of a union
is a type name. Like the built-in types, by default union
s are uninitialized. We can explicitly initialize a union
in the same way that we can explicitly initialize aggregate classes (§ 7.5.5, p. 298) by enclosing the initializer in a pair of curly braces:
Token first_token = {'a'}; // initializes the cval member
Token last_token; // uninitialized Token object
Token *pt = new Token; // pointer to an uninitialized Token object
If an initializer is present, it is used to initialize the first member. Hence, the initialization of first_token
gives a value to its cval
member.
The members of an object of union
type are accessed using the normal member access operators:
last_token.cval = 'z';
pt->ival = 42;
Assigning a value to a data member of a union
object makes the other data members undefined. As a result, when we use a union
, we must always know what type of value is currently stored in the union
. Depending on the types of the members, retrieving or assigning to the value stored in the union
through the wrong data member can lead to a crash or other incorrect program behavior.