A union is an object similar to a structure except that all of its members start at the same location in memory. A union can contain the value of only one of its members at a time. The default initializer for a union with static storage is the default for the first component; a union with automatic storage has none.
The storage allocated for a union is the storage required for the largest member of the union (plus any padding that is required so that the union will end at a natural boundary of its member having the most stringent requirements). For this reason, variably modified types may not be declared as union members. All of a union's components are effectively overlaid in memory: each member of a union is allocated storage starting at the beginning of the union, and only one member can occupy the storage at a time.
Any member of a union can be initialized, not just the first member, by
using a designator. A designated initializer for a union has the same
syntax as that for a structure. In the following example, the
designator is .any_member and the initializer is
{.any_member = 13 }:
union { /* ... */ } caw = { .any_member = 13 };
Each union definition creates a new union type that is neither the same as
nor compatible with any other union type in the same source file.
However, a type specifier that is a reference to a previously defined union
type is the same type. The union tag associates the reference with the
definition, and effectively acts as the type name.
In C++, a union is a limited form of the class type. It can contain
access specifiers (public, protected, private), member data, and member
functions, including constructors and destructors. It cannot contain
virtual member functions or static data members. Default access of
members in a union is public. A union cannot be used as a base class
and cannot be derived from a base class.
C++ places additional limitations on the allowable data types for a union member. In C++, a union member cannot be a class object that has a constructor, destructor, or overloaded copy assignment operator, nor can it be of reference type. A union member cannot be declared with the keyword static.
Related References