TITLE: Scoping and anonymous unions (Newsgroups: comp.std.c++, 17 Nov 97)a DANIELS: "Brad Daniels" >I ran into this case yesterday: > >class X { > enum { SIZE=100 }; > union { > double d; > char str[SIZE]; > }; >}; >VC++ (5.0) complains because the anonymous union can't see X::SIZE, and I >fear it may be right. The draft says in section 9-10, "For the purpose of >name look up, 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." The inclusion of the phrase "after the >anonymous union definition" seems to imply that the body of the union should >not be able to see its enclosing scope. HENDERSON: fjh@mundook.cs.mu.OZ.AU (Fergus Henderson) You are confusing name look up with access control. Names declared in the enclosing class are always *visible*, for the purposes of name look up, in nested classes -- and that includes nested anonymous unions. However, nested classes don't have *access* to private members of enclosing classes, unless explicitly declared friends. In the case of anonymous unions, there is no way to declare the anonymous union to be a friend. Perhaps it would be more useful if the draft said "For the purposes of name look up _or access control_, ...". DANIELS: >Of course, VC++ accepts the following: >class X { >public: > enum { SIZE=100 }; >private: > union { > double d; > char str[SIZE]; > }; >}; > >Which is OK for my immediate purposes, but doesn't seem at all consistent. >It seems to me I should need to say X::SIZE in the declaration of str to be >consistent. HENDERSON: The inconsistency here is just the usual inconsistency in C++ between name look up and accessibility. In many other languages (e.g. Ada), names which are not accessible are not visible, but in C++ a private member may be visible but not accessible. DANIELS: >I though a slightly cleaner approach might be: > >class X { > union { > enum { SIZE=100 }; > double d; > char str[SIZE]; > }; >}; HENDERSON: This example is ill-formed, by 9.5[class.union]/2: "The member-specification of an anonymous union shall only defined non-static data members". Here the member-specification of your anonymous union defines `SIZE', which is not a non-static-data-member, so it is ill-formed. A diagnostic is required. [snip]