Anonymous Unions

Anonymous unions are unions that are declared without a class-name or declarator-list.

Syntax

union { member-list } ;

Such union declarations do not declare types—they declare objects. The names declared in an anonymous union cannot conflict with other names declared in the same scope.

Names declared in an anonymous union are used directly, like nonmember variables. The following example illustrates this:

#include <iostream.h>

struct DataForm

{

enum DataType { CharData = 1, IntData, StringData };

DataType type;

// Declare an anonymous union.

union

{

char chCharMem;

char *szStrMem;

int iIntMem;

};

void print();

};

void DataForm::print()

{

// Based on the type of the data, print the

// appropriate data type.

switch( type )

{

case CharData:

cout << chCharMem;

break;

case IntData:

cout << szStrMem;

break;

case StringData:

cout << iIntMem;

break;

}

}

In the function DataForm::print, the three members (chCharMem, szStrMem, and iIntMem) are accessed as though they were declared as members (without the union declaration). However, the three union members share the same memory.

In addition to the restrictions listed in “Union Member Data”, anonymous unions are subject to additional restrictions:

They must also be declared as static if declared in file scope.

They can have only public members; private and protected members in anonymous unions generate errors.

They cannot have function members.

Note:

Simply omitting the class-name portion of the syntax does not make a union an anonymous union. For a union to qualify as an anonymous union, the declaration must not declare an object.