Is it possible to put several objects together inside a union?

Current C++ standard does not allow non-POD types inside unions. You will get this compiler error from gcc:

error: member ‘std::vector<int, std::allocator<int> >
<anonymous union>::i’ with constructor not allowed in union
error: member ‘std::vector<int, std::allocator<int> >
<anonymous union>::i’ with destructor not allowed in union

New C++ standard (C++0x) proposes unrestricted unions, but it adds yet more object lifetime pitfalls to C++.


You cannot have unions containing non-POD class types. Your sample will not compile.

You can use boost::variant as a safe alternative to C unions. See the documentation on boost.org. You might, however, reconsider your design and use polymorphism instead. Depends on what you're trying to accomplish, of course.

Tags:

C++

Unions