[class.union.anon] (original) (raw)
11 Classes [class]
11.5 Unions [class.union]
11.5.2 Anonymous unions [class.union.anon]
A union of the form
is called an anonymous union; it defines an unnamed type and an unnamed object of that type called an anonymous union memberif it is a non-static data member or an anonymous union variable otherwise.
Nested types, anonymous unions, and functions shall not be declared within an anonymous union.
The names of the members of an anonymous union are bound in the scope inhabited by the union declaration.
[Example 1: void f() { union { int a; const char* p; }; a = 1; p = "Jennifer";}
Here a and p are used like ordinary (non-member) variables, but since they are union members they have the same address.
— _end example_]
An anonymous union declared in the scope of a namespace with external linkage shall use the storage-class-specifier static.
Anonymous unions declared at block scope shall not use a storage-class-specifierthat is not permitted in the declaration of a block variable.
[Note 1:
A union for which objects, pointers, or references are declared is not an anonymous union.
[Example 2: void f() { union { int aa; char* p; } obj, *ptr = &obj; aa = 1; ptr->aa = 1; }
The assignment to plain aa is ill-formed since the member name is not visible outside the union, and even if it were visible, it is not associated with any particular object.
— _end example_]
— _end note_]
[Note 2:
Initialization of unions with no user-declared constructors is described in [dcl.init.aggr].
— _end note_]
A union-like class is a union or a class that has an anonymous union as a direct member.
A union-like class X has a set of variant members.
If X is a union, a non-static data member of X that is not an anonymous union is a variant member of X.
In addition, a non-static data member of an anonymous union that is a member of X is also a variant member of X.
At most one variant member of a union may have a default member initializer.
[Example 3: union U { int x = 0;union { int k;};union { int z;int y = 1; };}; — _end example_]