Jump to content

  • Log In with Google      Sign In   
  • Create Account

Banner advertising on our site currently available from just $5!


1. Learn about the promo. 2. Sign up for GDNet+. 3. Set up your advert!


C++: Union, struct and default constructor


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 DaBono   Members   -  Reputation: 1186

Like
0Likes
Like

Posted 28 July 2009 - 12:46 AM

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?

Sponsor:

#2 Sc4Freak   Members   -  Reputation: 643

Like
0Likes
Like

Posted 28 July 2009 - 12:59 AM

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).

#3 phresnel   Members   -  Reputation: 949

Like
0Likes
Like

Posted 28 July 2009 - 01:16 AM

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.

#4 Nitage   Members   -  Reputation: 810

Like
0Likes
Like

Posted 28 July 2009 - 03:05 AM

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?




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS