Using a union
Type
The 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 memberToken last_token; // uninitialized Token objectToken *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 ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.