Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Statically initialize anonymous union in C++

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?

like image 508
wpfwannabe Avatar asked Jun 13 '10 08:06

wpfwannabe


People also ask

What is anonymous union in C?

An anonymous union is a union without a name. It cannot be followed by a declarator. An anonymous union is not a type; it defines an unnamed object.

Can we initialize union in C?

C allows you to initialize a union in two ways: Initialize a union by initializing the first member of a union. Or initialize a union by assigning it to another union with the same type.

How do you initialize a union?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).

Can we initialize unions?

Using designated initializers, a C99 feature which allows you to name members to be initialized, structure members can be initialized in any order, and any (single) member of a union can be initialized.


2 Answers

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.

like image 101
Pavel Minaev Avatar answered Sep 25 '22 06:09

Pavel Minaev


Can you do it by defining overloaded constructors? Untested code ahead:

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

    Data()
    {
        x = 0;
        y.data = 0;
        y.z.a = 0;
        y.z.b = 0;
    }

    Data(int x_, Data* data_)
    {
        x = x_;
        y.data = data_;
    }

    Data(int x_, int a_, int b_)
    {
        x = x_;
        y.z.a = a_;
        y.z.b = b_;
    }
}; 

static Data d1; 
static Data d(1, &d1); 
static Data d2(1, 1, 2); 
like image 30
ChrisW Avatar answered Sep 24 '22 06:09

ChrisW