Statically initialize anonymous union in C++

wpfwannabe picture wpfwannabe · Jun 13, 2010 · Viewed 7.6k times · Source

I am trying to statically initialize the following structure in Visual Studio 2010:

struct Data
{
   int x;
   union
   {
      const Data* data;
      struct {int x; int y; };
   };
};

The following is fails with error C2440: 'initializing' : cannot convert from 'Data *' to 'char'.

static Data d1;
static Data d = {1, &d1};
static Data d2 = {1, {1, 2}};

I have found references to some ways this can be initialized properly but none of them work in VS2010. Any ideas?

Answer

Pavel Minaev picture Pavel Minaev · Jun 13, 2010

ISO C++03 8.5.1[dcl.init.aggr]/15:

When a union is initialized with a brace-enclosed initializer, the braces shall only contain an initializer for the first member of the union. [Example:

union u { int a; char* b; };
u a = { 1 };
u b = a;
u c = 1; // error
u d = { 0, "asdf" }; // error
u e = { "asdf" }; // error

—end example]

So, generally speaking, it can't be done.