-2

I have this piece of code:

class test {
  private:
  union {
    double x;
    std::vector<double> y;
  } amIValid;
};

I wonder if the union instance amIValid is valid?

timrau
  • 22,578
  • 4
  • 51
  • 64
Pekov
  • 527
  • 1
  • 9
  • 23
  • when you compiled it, what happened? – UKMonkey Dec 07 '17 at 12:04
  • Possible duplicate of [Why does C++ disallow anonymous structs and unions?](https://stackoverflow.com/questions/2253878/why-does-c-disallow-anonymous-structs-and-unions) – underscore_d Dec 07 '17 at 12:15
  • `gcc` gives me this: `note: ‘test::::()’ is implicitly deleted because the default definition would be ill-formed:|` – Pekov Dec 07 '17 at 12:17
  • 1
    So you answered your own question before even posting it? Yes, you need to provide a constructor in such cases, to ensure a single member is active after the object is initialised. – underscore_d Dec 07 '17 at 12:19
  • 3
    Strictly speaking, you don't have an anonymous union. You have a member of an unnamed union type. Anonymous unions inject their members into the enclosing class/union. – StoryTeller - Unslander Monica Dec 07 '17 at 12:28

1 Answers1

2

An unnamed union can be instantiated in C++:

union { int i; double d; } my_thing;
my_thing.i = 3;
// etc.

An anonymous union is an unnamed union that is not instantiated (scroll down). You can access its members directly:

union { int i; double d; };
i = 3;
// etc.

So the answer to the question in the title is that an anonymous union cannot be instantiated because instantiating it means that it is not an anonymous union.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165