Usage of union inside a class

q0987 picture q0987 · Mar 28, 2011 · Viewed 13.4k times · Source

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?

Answer

Jon Hanna picture Jon Hanna · Mar 28, 2011

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.