[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 object.
Nested types, anonymous unions, and functions shall not be declared within an anonymous union.
The names of the members of an anonymous union shall be distinct from the names of any other entity in the scope in which the anonymous union is declared.
For the purpose of name lookup, after the anonymous union definition, the members of the anonymous union are considered to have been defined in the scope in which the anonymous union is declared.
[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_]
Anonymous unions declared in a named namespace or in the global namespace shall be declared static.
Anonymous unions declared at block scope shall be declared with any storage class allowed for a block-scope variable, or with no storage class.
A storage class is not allowed in a declaration of an anonymous union in a class scope.
[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_]