36

I would like to know the difference between structure and union for one member data type if there is any.

codenheim
  • 20,467
  • 1
  • 59
  • 80
RAFI KC
  • 421
  • 4
  • 8
  • 4
    you can read about that yourself by a simple search on Google. –  Oct 26 '14 at 11:27
  • 14
    @Begueradj: Maybe, but the point is somewhat subtle, and I might not be inclined to trust the first thing Google throws at me. – Kerrek SB Oct 26 '14 at 11:34
  • 2
    Concerning POD and aggregates with additional discussion of changes for C++11 see [What are aggregates and PODs and how are they special](http://stackoverflow.com/questions/4178175/what-are-aggregates-and-pods-and-how-why-are-they-special) – Richard Chambers Oct 26 '14 at 12:45
  • Instead of closing, maybe move to Programmers? – wberry Oct 26 '14 at 19:50

1 Answers1

37

In C: None. The famous "space-saving joke" #define struct union is almost not a joke.

In C++98: Unions can only have POD members, non-union classes can have arbitrary members.

In C++11: Unions can have arbitrary data members of object type (but not of reference type), but their use is more restricted that that of non-union classes. (Namely: a union cannot have virtual member functions, cannot be a base class and cannot have base classes.) Also, you have to write more code to make a one-member union work as opposed to a one-member non-union class, since you have to write constructors and the destructor yourself.

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 1
    Isn't an implementation allowed to have padding in a structure, but not in a union? – mafso Oct 26 '14 at 12:03
  • @mafso: I don't think so. The only constraint I see is this: "The size of a union is sufficient to contain the largest of its non-static data members." – Kerrek SB Oct 26 '14 at 12:11
  • 1
    No padding allowed *before* the first member of a struct and there may be padding at the end for both union and structure. So no difference as far as single member union vs struct is concerned. – P.P Oct 26 '14 at 12:14
  • 1
    Maybe worth a quick one-line shout-out to readability and maintainability (i.e. doesn't break when you add member #2). – djechlin Oct 26 '14 at 15:22