Using a union Type
The name of a union is a type name. Like the built-in types, by default unions 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access