How to initialize a member of union type

A

alexwu

typedef union _MYUNION

struct {
short a;
short b;
};
long c;
} MYUNION;


class myclass
{
MYUNION myu;
public:
myclass();
};


// How to initialize myu in the constructor initializer list
myclass::myclass()
{
....
}
 
J

John Harrison

alexwu said:
typedef union _MYUNION

struct {
short a;
short b;
};
long c;
} MYUNION;


class myclass
{
MYUNION myu;
public:
myclass();
};


// How to initialize myu in the constructor initializer list
myclass::myclass()
{
...
}

You cannot. Unions to not have constructors and therefore cannot be
initialised; only assigned to.

john
 
R

Rob Williscroft

John Harrison wrote in in
comp.lang.c++:

To the OP: Anonymous struct's aren't Standard C++, you *must*
declare/define something.
short a;
short b;
};
long c;
} MYUNION;
[...]


You cannot. Unions to not have constructors and therefore cannot be
initialised; only assigned to.

sed s/Unions/Aggregate types/

I.e. array's and constructor-free struct's have the same problem.

However union's with a user defined constructor don't:

#include <iostream>

union my_union
{
int i;
double d;
my_union( int ii ) : i( ii ) {}
};

int main()
{
std::cout << my_union( 1 ).i << '\n';
}

Also you can use *value-initialization* with unions:

#include <iostream>
#include <ostream>

union my_union
{
int i;
double d;
};

struct X
{
my_union m;
X() : m() {}
};

int main()
{
std::cout << X().m.i << '\n';
}

Which should, assuming IIUC and its put through a recient Standard
conforming compiler print 0.

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top