C++: Union, struct and default constructor

Started by
2 comments, last by Nitage 14 years, 9 months ago
Quick question regarding unions. I understand why a type I put in a union has to have a trivial default constructor. So my class definition is:
class MyClass {
   public:
      MyClass() {}
      MyClass(...) { /* other constructor */ }
};
Now when I declare a union like so:
union MyUnion {
   int numbers[4];
   MyClass instance;
};

my compiler (the one in Visual Studio 2005 SP1) complains that MyClass has a non-trivial default constructor. However, this compiles without problem:
union MyUnion {
   int numbers[4];
   struct {
      MyClass instance;
   };
};

Can somebody enlighten me why this does work?
Advertisement
The rule is that POD types can have no user-defined constructors (which are regarded as "non-trivial"). I'm actually surprised the second example works; a POD type can only contain other POD types as data members. Logically, the anonymous struct should also be non-POD. Although I'm not certain what the standard mandates here (or even if anonymous structs inside a union are technically legal).
NextWar: The Quest for Earth available now for Windows Phone 7.
If we make it conformant ...

union MyUnion {   int numbers[4];   struct {      MyClass instance;   } x; // << anonymous structs not allowed, hence declare an instance};


... then g++ will not compile this.
The anonymous struct isn't legal C++ - it's a compiler extension. Allowing you to add a non-pod class to a union looks like a bug in that extension.

Does the constructor actually get run?

This topic is closed to new replies.

Advertisement