Unions

A union is a user-defined data or class type that, at any given time, contains only one object from its list of members. The object can be an array or a class type).

union [tag]  { member-list } [declarators];
[union] tag declarators;

Parameters

  • tag
    The type name given to the union.

  • member-list
    List of the types of data the union can contain. See Remarks.

  • declarators
    Declarator list specifying the names of the union. See Overview of Declarators for more information.

Remarks

The member-list of a union represents the kinds of data the union can contain. A union requires enough storage to hold the largest member in its member-list. For more information, refer to Union Declarations (C Language Reference).

Declaring a Union

Begin the declaration of a union with the union keyword, and enclose the member list in curly braces:

// declaring_a_union.cpp
union DATATYPE    // Declare union type
{
    char   ch;
    int    i;
    long   l;
    float  f;
    double d;
    int *int_ptr;
} var1;          // Optional declaration of union variable

int main()
{
}

Using a Union

A C++ 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 functions or static data members. It cannot be used as a base class, nor can it have base classes. The default access of members in a union is public.

In C++, you do not need to use the union keyword when you declare a union variable.

DATATYPE var3;         // C++ declaration of a union variable

A variable of a union type can hold one value of any type declared in the union. Use the member-selection operator (.) to access a member of a union:

var1.i = 6;           // Use variable as integer
var2.d = 5.327;       // Use variable as double 

You can declare and initialize a union in the same statement by assigning an expression enclosed in braces. The expression is evaluated and assigned to the first field of the union.

Example

#include <iostream>
using namespace std;

union NumericType
{
    int         iValue;
    long        lValue;  
    double      dValue;  
};

int main()
{
    union NumericType Values = { 10 };   // iValue = 10
    cout << Values.iValue << '\n';
    Values.dValue = 3.1416;
    cout << Values.dValue);
}

Output

10
3.141600

The NumericType union is arranged in memory (conceptually) as shown in the following figure.

Storage of Data in NumericType Union

Storage of data in a numeric type union

See Also

Reference

Classes, Structures, and Unions

C++ Keywords

Anonymous Unions

class (C++)

struct (C++)