Home > OS >  Why a class with in-class initialization can't be used as member of a union?
Why a class with in-class initialization can't be used as member of a union?

Time:04-19

I have the following code

#include <iostream>
using namespace std;

struct S{
    int a = 0;
    S() = default;
};

union U {
    S s;
    int i;
};

int main() {
    U u;
    u.s.a = 1;
    return 0;
}

However, it can't compile and issues the following errors

prog.cpp: In function ‘int main()’:
prog.cpp:15:4: error: use of deleted function ‘U::U()’
  U u;
    ^
prog.cpp:9:7: note: ‘U::U()’ is implicitly deleted because the default definition would be ill-formed:
 union U {
       ^
prog.cpp:10:4: error: union member ‘U::s’ with non-trivial ‘constexpr S::S()’
  S s;
    ^

However when I modify the definition of U by adding a default constructor, it compiles.

union U {
    S s;
    int i;
    U() {
 
    }
};

My question is why the code can't compile without a given default constructor? Do we have something in the C standard to explain this?

My guess is C prohibits a implicit default constructor if a union has non-trivial member. And a class with in-class initialization members is non-trivial. Am I right?

CodePudding user response:

Union cannot contain "non trivial" members: see here. "trivial" means that the member should do nothing on its constructor. Setting a to 0 is doing something, so the union cannot contain this member.

CodePudding user response:

Your union has two members. At any time, one of the two members is active, and a constructor must make one of them active, but a default constructor cannot know which one.

  •  Tags:  
  • c
  • Related