Unions
A union is a class type in which all data members share the same memory location. In C++, a union may include both member functions and data. In a union, all of its members are public by default. To create private elements, you must use the private keyword. The general form for declaration of a union is
union class-name {
// public members by default
private:
// private members
} object-list;>
In C, unions may contain only data members and the private keyword is not supported.
The elements of a union overlay each other. For example,
union tom { char ch; int x; } t; declares union tom, which looks like this in memory (assuming 2-byte integers):
Like a class, the individual variables that comprise the union are referenced using the dot operator. The arrow operator is used with a pointer to a union.
There are several restrictions that apply to unions. First, a union cannot inherit any other class of any type. A union cannot be a base class. A union cannot have virtual member functions. No members may be declared as static. A reference member cannot be used. A union cannot have as a member any object that overloads the = operator. Finally, no object can be a member of a union if the object’s class explicitly defines a constructor or destructor function. (Objects that have only the default constructors and destructors are acceptable.)