Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I initialize a union in a mem-initializer?

Tags:

c++

I'm surprised this doesn't work:

union DlDatum
{
   float  mFloat;
   s32    mInteger;
};

class DlDbE
{
public:
   DlDbE( float f ) : mData.mFloat( f ) {};
private:
   DlDatum mData;
};

Is there a way to initialize a union in a c++ constructor mem-initializer list?

Update: Answer is to create constructors for union. Didn't know that could be done. Here is what I did:

union DlDatum
{
   float  mFloat;
   s32    mInteger;
   bool   mBoolean;
   u32    mSymbol;
   u32    mObjIdx; 

   DlDatum(         ) : mInteger( 0 ) {}
   DlDatum( float f ) : mFloat( f )   {}
   DlDatum( s32   i ) : mInteger( i ) {}
   DlDatum( bool  b ) : mBoolean( b ) {}
   DlDatum( u32   s ) : mSymbol( s )  {} // this ctor should work for objIdx also
};

class DlDbE
{
public:
   DlDbE() {}
   DlDbE( float f ) : mData( f ) {}
   DlDbE( u32 i   ) : mData( i ) {}
   DlDbE( bool b  ) : mData( b ) {}
   ...etc..
private:
   DlDatum mData;
};
like image 472
Rafael Baptista Avatar asked Oct 24 '12 19:10

Rafael Baptista


1 Answers

In C++03 and before you are limited to writing a constructor for your union.

In C++11 the uniform initialization extents the syntax of aggregate initialization to constructor initializer lists. This means that the good old aggregate initializer syntax like

DlDatum d = { 3.0 };

which we all know and love from C and which initializes the first member of the union, can now be used in constructor initializer lists as well

union DlDatum
{
   float  mFloat;
   s32    mInteger;
};

class DlDbE
{
public:
   DlDbE( float f ) : mData{f} {}
private:
   DlDatum mData;
};

This feature only allows you to "target" the first non-static member of the union for initialization. If you need something more flexible, then it is back to writing constructors.

like image 106
AnT Avatar answered Nov 07 '22 09:11

AnT