union
s with Members of Class TypeUnder earlier versions of C++, union
s could not have members of a class type that defined its own constructors or copy-control members. Under the new standard, this restriction is lifted. However, union
s with members that define their own constructors and/or copy-control members are more complicated to use than union
s that have members of built-in type.
When a union
has members of built-in type, we can use ordinary assignment to change the value that the union
holds. Not so for union
s that have members of nontrivial class types. When we switch the union
’s value to and from a member of class type, we must construct or destroy that member, respectively: When we switch the union
to a member of class type, we must run a constructor for that member’s type; when we switch from that member, we must run its destructor.
When a union
has members of built-in type, the compiler will synthesize the memberwise versions of the default constructor or copy-control members. The same is not true for union
s that have members of a class type that defines its own default constructor or one or more of the copy-control members. If a union
member’s type defines one of these members, the compiler synthesizes the corresponding member of the union
as deleted (§ 13.1.6, p. 508).
For example, the string
class defines all five copy-control members and the default constructor. If a union
contains a string
and does not define its own default constructor or one of the copy-control members, then the compiler will synthesize that missing member as deleted. If a class has a union
member that has a deleted copy-control member, then that corresponding copy-control operation(s) of the class itself will be deleted as well.