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?
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.