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;
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With