I saw some code as follows:
class A
{
private:
union {
B *rep;
A *next;
}; // no variables of this anonymous defined!
void func()
{
A *p = new A;
p->next = NULL; // why p has a member variable of 'next'?
}
};
I have compiled the above code with VS2010 without any error. Here is the question,
why p has member variable 'next'?
union {
B *rep;
A *next;
};
As far as I know, this is an anonymous union without even defining a variable. How can we access the member variables inside this union like that?
A structure can be nested inside a union and it is called union of structures. It is possible to create a union inside a structure.
A union is an object similar to a structure except that all of its members start at the same location in memory. A union variable can represent the value of only one of its members at a time. In C++, structures and unions are the same as classes except that their members and inheritance are public by default.
A union is a user-defined type in which all members share the same memory location. This definition means that at any given time, a union can contain no more than one object from its list of members.
A union is a special class type that can hold only one of its non-static data members at a time. The class specifier for a union declaration is similar to class or struct declaration: union attr class-head-name { member-specification } attr.
Because that's pretty much what an anonymous union does, it defines zero-or-more variables in the enclosing namespace (which in a class declaration makes them field names) which occupy overlapping memory. Hence in use it's the same as if you'd declared
class A
{
private:
B *rep;
A *next;
void func()
{
A *p = new A;
p->next = NULL;
}
};
...except for rep and next occupying overlapping space (or given that the two pointers will have the same size, the same space), and hence all the dangers and benefits that come with a named union.
Here's the quote from the standard that controls this behavior: section [class.union]
(wording from C++0x draft n3242)
A union of the form
union {
member-specification} ;
is called an anonymous union; it defines an unnamed object of unnamed type. The member-specification of an anonymous union shall only define non-static data members. [ Note: Nested types and functions cannot be declared within an anonymous union. — end note ] 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With