24

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)

timrau
  • 22,578
  • 4
  • 51
  • 64
Jason S
  • 184,598
  • 164
  • 608
  • 970
  • I don't see anything wrong with them except what you mentioned about the destructors and the freeing memory. – Jim Oct 29 '10 at 22:14
  • 1
    This is exactly why you can't have union members of a class/struct type that has a non-trivial constructor, destructor or assignment operator. – Oliver Charlesworth Oct 29 '10 at 22:19

2 Answers2

30

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.

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

Eugen Constantin Dinca
  • 8,994
  • 2
  • 34
  • 51
-11

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.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 3
    Don't forget the embedded world. Sometimes things aren't 100% typesafe. – Jason S Oct 29 '10 at 23:30
  • @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. – Puppy Oct 29 '10 at 23:41
  • 6
    Embedded doesn't change anything about the language per se, but it does place limits on dynamic memory allocation and polymorphism (& much of boost is out) that bias you towards other techniques. Most often is a union between two 16-bit #s and a 32-bit #, or a union between a 16- or 32-bit # and a struct with bitfields. In those cases both members of the union have equally valid contents; it's both types. – Jason S Oct 29 '10 at 23:59
  • 12
    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 Oct 30 '10 at 02:38