A union is an object that can hold any one of a set of named members. Members of a union are declared public by default. The members of the named set can be of any data type.
Unions
can also consist of member functions, including constructors and
destructors, but no virtual functions. A union cannot be used as
a base class and cannot be derived from a base class. A C++ union
member cannot be a class object that has a constructor,
destructors, overloaded copy assignment operator. In C++, a
member of a union cannot be declared with the keyword static.
Syntax:
union [ identifier ] { [ member_specification ]+ };
The following example of a union stores the apartment number, if the address is that of an apartment complex:
union house_type {
char motorhome;
char apartment;
char townhouse;
char mansion;
};
One of the following declarations can be made:
union house_type primary_residence; // explicit union specification
or
house_type primary_residence; // In C++, the union keyword is not necessary house_type *p_primary_residence = &primary_residence;
To refer to a particular field in the house_type union, one of the following methods can be applied:
primary_residence.townhouse = 'Y';
or
p_primary_residence -> townhouse = 'Y';
Anonymous Unions in C
Unions declared without declarators are known as anonymous
unions.
Anonymous unions can be declared by one of two methods:
typedef union {
char leftwing;
char rightwing;
char defense;
char goaltender;
char centre;
} POSITION;
struct hockey_player {
char name[10];
int age;
POSITION;
float height;
};
union POSITION {
char leftwing;
char rightwing;
char defense;
char goaltender;
char centre;
};
struct hockey_player {
char name[10];
char team[15];
union POSITION;
} myfavorite;
For more information about anonymous unions in C++, refer to Stroustrup, Appendix C.
