Class which have user-defined constructor or user-defined destructor is not allowed in union
.
You can have pointer of such class as member of union, though.
struct X
{
X() {}
~X() {}
};
union A
{
X x; // not allowed - X has constructor (and destructor too)
X *px; //allowed!
};
Or you can use boost::variant
which is a safe, generic, stack-based discriminated union container.
ยง9.5/1 says (formatting and emphasize is mine)
- A union can have member functions (including constructors and destructors), but not virtual (10.3) functions.
- A union shall not have base classes.
- A union shall not be used as a base class.
- An object of a class with a non-trivial constructor (12.1), a non-trivial copy constructor (12.8), a non-trivial destructor (12.4), or a non-trivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union, nor can an array of such objects.
- If a union contains a static data member, or a member of reference type, the program is ill-formed.
Interesting!