11

In C++11 one can do

struct S {int i = 42;};

and if one forgets to initialize the member i it gets default initialized to 42. I Just tried this with bitfields as

struct S {int i = 42 : 5;};

and am getting

error: expected ';' before ':' token

Does this feature exist for bitfield members and if so, how do I use it?

Vorac
  • 8,726
  • 11
  • 58
  • 101
  • 2
    Seems like it will eventually appear in C++20 :-) http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0683r1.html – Bo Persson Dec 09 '17 at 10:24
  • Possible duplicate of [Bit-fields "In-class initialization" results in "error: lvalue required as left operand of assignment"](https://stackoverflow.com/questions/16520701/bit-fields-in-class-initialization-results-in-error-lvalue-required-as-left) – WorldSEnder Feb 15 '18 at 13:24

3 Answers3

19

The syntax for bit field initialization is

 struct S {int i: 5 = 42;};

and is only available in c++20: -std=c++2a for now

Charles Gueunet
  • 1,708
  • 14
  • 14
  • 1
    In case anyone else is looking, https://clang.llvm.org/cxx_status.html#cxx2a indicates you need clang 6.0 for this – Goblinhack Dec 01 '18 at 15:56
8

No, bit-fields do not allow an initializer as part of the member declaration. You can see this in the part of the grammar that describes class members (C++11 and later, [class.mem]):

member-declarator:
    declarator virt-specifier-seqopt pure-specifieropt
    declarator brace-or-equal-initializeropt
    identifieropt attribute-specifier-seqopt : constant-expression

The third form is the grammar for a bit-field declaration, but only the second form lists the brace-or-equal-initializer.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
4

You can also use a constructor to initialize a bitfield like this:

struct Foo {
    Foo () : i {15} {}

    int i : 5;
};

Foo foo;
cout << foo.i << endl; // 15

You can see it here

Artur Pyszczuk
  • 1,920
  • 1
  • 16
  • 23