3

let's say I have a Union like this :

union checkUnion{
    std::string* str;
    bool someBool;
    int aNumber;
};

How can I check which of these 3 items has been chosen during the program? I want to do individual if-queries for each of the items.

e.g.: [Pseudo-Code]

if (checkUnion == string)
{
   //CODE
}

if (checkUnion == bool)
{
   //DIFFERENT CODE
}
timrau
  • 22,578
  • 4
  • 51
  • 64
user3085931
  • 1,757
  • 4
  • 29
  • 55
  • 4
    You can't, you need to have a discriminator member stored *outside* the union. A union itself stores only as much information as you put in it, and no more. If you find yourself needing this, you should probably rethink your design, and look into subclasses and virtual methods. – user4815162342 Jul 07 '14 at 09:46

1 Answers1

6

You can't. You either need to know beforehand the initialized value, or add the union to some larger struct. See this other SO question.

Update:

Unions on C++ are just for compatibility with C code, and you'd rarely need them. Even if you are creating some fancy network protocol you'd use a tool like google-protobuf than a hand-crafted union. The original objective on unions was to overlap bytes on different fields or structures, to save as many bytes as possible on those data structures while retaining compiler support.

On C++ you'd beter create a class hierarchy, and each variant as a subclass of a base class. Internally you will also have a discriminator, the C++ vtable, but the discrimination is handled by the compiler. Which is better maintainable and less error prone than hand crafted unions.

Community
  • 1
  • 1
vz0
  • 32,345
  • 7
  • 44
  • 77
  • I don't get the sense of a union type then. It was designed to save some space, as far as I understood. So now you need another variable, that "wastes" some additional space, just to determine how you can use this union-variable ? This means, in the end you could come up wasting more memory than when defining the items by themselves - pretty useless then, or did I understood it wrong ? – user3085931 Jul 07 '14 at 11:18
  • 1
    If the variable contains useful data then it is not a waste at all. The waste would be to replace the union with an struct, having lots of unused fields each with its own memory. I've updated my answer. – vz0 Jul 07 '14 at 13:34
  • Thanks for the update it was very informative. Anyways, if I'd like to use my code on an embedded device every bit of memory counts - so it's actually pretty useful to work with unions. Can't imagine, that this memory saving option, comes in this unhandy. – user3085931 Jul 07 '14 at 13:52