union
: A Space-Saving ClassA union
is a special kind of class. A union
may have multiple data members, but at any point in time, only one of the members may have a value. When a value is assigned to one member of the union
, all other members become undefined. The amount of storage allocated for a union
is at least as much as is needed to contain its largest data member. Like any class, a union
defines a new type.
Some, but not all, class features apply equally to union
s. A union
cannot have a member that is a reference, but it can have members of most other types, including, under the new standard, class types that have constructors or destructors. A union
can specify protection labels to make members public
, private
, or protected
. By default, like struct
s, members of a union
are public
.
A union
may define member functions, including constructors and destructors. However, a union
may not inherit from another class, nor may a union
be used as a base class. As a result, a union
may not have virtual functions.