0
struct data { uint8_t nibble1 : 4, nibble2 : 4; constexpr data() { nibble1 = 2; nibble2 = 4; } }; 

This gives me the following two compilation errors on GCC 9.2.0:

error: member 'data::nibble1' must be initialized by mem-initializer in 'constexpr' constructor error: member 'data::nibble2' must be initialized by mem-initializer in 'constexpr' constructor 

But I'm pretty sure my constructor intialises both of them. I've taken a look at https://en.cppreference.com/w/cpp/language/constexpr and I don't see any requirements which my constexpr constructor doesn't satisfy.

How can I get rid of this error?

1
  • You are assigning to both of them. You are not initializing them with the values. Commented Dec 30, 2019 at 15:20

1 Answer 1

3

You need to initialize the members with a member initializer list:

constexpr data() : nibble1(2), nibble2(4) { } 

The page you linked show the following requirements for constexpr constructors:

  • for the constructor of a class or struct, every base class sub-object and every non-variant non-static data member must be initialized.

But this:

nibble1 = 2; 

...is not an initialization for nibble1, it's an assignment. The only way to initialize member variables is to use a member initializer list or to default them (which is not possible for bit-fields until C++20 I think).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.