mc said:
Is it possible to initialize a bitfield with an initialization list? If
yes, what is the syntax?
typedef struct
{
unsigned a : 1;
unsigned b : 1;
} bf;
class Foo
{
Foo() : bf(false, false)
{
}
};
This and other attempts were unsuccessful.
You need to state more precisely what is it your are trying to do. 'bf'
is just a typedef name, not a member or base name of 'Foo', which means
that using it in the constructor initializer list the way it is used in
the above example simply makes no sense whatsoever.
Bitfields are no different from any other data members. They can be
initialized in just like any other data members. For a standalone 'bf'
object (as declared above) it can be done with an aggregate initializer
bf s = { false, true };
However, aggregate initializer cannot be used in constructor initializer
lists, which means that if in class 'Foo' you have a data member of type
'bf' (as declared above) the only option you have is to use the '()'
initializer
class Foo {
bf s;
Foo() : s() {}
};
This will set all members of 's' to '0'.
But if you want to use specific values for each bitfield in 'bf', you'll
have to provide a user-declared constructor that does what you need. And
you'll have to give your struct a real name (why would you use such a
typedef in C++ anyway)
struct bf {
unsigned a : 1;
unsigned b : 1;
bf(bool a, bool b) : a(a), b(b) {}
};
class Foo {
bf s;
Foo() : s(false, true) {}
};