tags:

views:

104

answers:

2

Is there anything wrong with a union having one or more methods? Or anything to watch out for? (I can see constructors/destructors being problematic for schizophrenic reasons)

A: 

How could you possibly implement such a thing? Here's a pointer to a union, hope you don't mind that you have no idea which variables are safe to use and which aren't.

Unions are a dead language feature really anyway- they've been totally superseded by library-based methods like boost::variant or boost::any. Kind of similar to the void* and functional macros - they're very rarely useful in C++ compared to other options.

DeadMG
Don't forget the embedded world. Sometimes things aren't 100% typesafe.
Jason S
@Jason: How does being embedded change anything? Either you know what type it is, so use a regular variable, you know all the types are related, so use polymorphism, or you need to know what type it is before you can do anything.
DeadMG
@DeadMG: Embedded doesn't change anything about the language per se, but it does place limits on dynamic memory allocation and polymorphism ( it's both types.
Jason S
One of C++'s strengths is that it does not forget that it is actually running on real world hardware, and unions are one of the tools that can greatly simplify this work.
Rob K
+6  A: 

From the C++03 & C++0x (Draft N3092) standards:

9.5 Unions
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.shall not be used as a base class.

As long as initializing the union using the aggregate initializer syntax (U u = { 42 };) or setting a member afterwards (U u; u.i = 42;) is not "problematic" initializing it using a constructor (U u( 42 );) is not "problematic" either.
The only "catch" is that you cannot use the aggregate initializer syntax for a union that has a user defined constructor.

Eugen Constantin Dinca
is this new for C++0x, or has it been part of the C++ standard?
Jason S
@Jim: That part is unchanged.
Eugen Constantin Dinca
unions can have constructors? then when is/isn't construction a problem?
Jason S