Using a Class to Manage union
Members
Because of the complexities involved in constructing and destroying members of class type, union
s with class-type members ordinarily are embedded inside another class. That way the class can manage the state transitions to and from the member of class type. As an example, we’ll add a string
member to our union
. We’ll define our union
as an anonymous union
and make it a member of a class named Token
. The Token
class will manage the union
’s members.
To keep track of what type of value the union
holds, we usually define a separate object known as a discriminant. A discriminant lets us discriminate among the values that the union
can hold. In order to keep the union
and its discriminant in sync, we’ll make the ...
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.