0

The following C++ code fails to compile. As far as I have looked into this problem, I understand that the problem is because the default constructor of the union has been deleted by the compiler. The online note says the following:

If a union contains a non-static data member with a non-trivial default constructor, the default constructor of the union is deleted by default unless a variant member of the union has a default member initializer.

struct A {
   int val;
   A() : val(0) {}
};

union B
{
   A a;
};

B b;

Why is the default constructor of struct A considered non-trivial? How do I work around this problem to make this code compile successfully?

Rakesh Agarwal
  • 3,009
  • 9
  • 33
  • 40

1 Answers1

0

Why is the default constructor of struct A considered non-trivial?

Because it is user-declared.

Examples of classes that do have a trivial constructor:

struct Trivial {
    int val;
};

struct Trivial2 {
    int val;
    Trivial2() = default;
};

As a bonus, this is non-trivial:

struct NonTrivial {
    int val;
    NonTrivial();
};
NonTrivial::NonTrivial = default;

If you want A::val to be zero-initialised however, you'll want to add a default member initialiser to the union:

union B {
   A a = {};
};
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • @DavisHerring I'm not sure what you refer to. Is it what I appended to the answer? – eerorika Feb 03 '19 at 15:46
  • That’s it (or just `A a{};`)—but it’s default-initialized, not zero-initialized, even though `val` does become 0. The important bit is that it makes `B` have a default constructor. – Davis Herring Feb 03 '19 at 16:48