In C++, I have a class which contains an anonymous bitfield struct. I want to initialize it to zero without having to manually write out all fields.
I can imagine putting the initialization in three places:
This bitfield has many fields, and I'd rather not list them all.
For example see the following code:
class Big {
public:
Big();
// Bitfield struct
struct bflag_struct {
unsigned int field1 : 1;
unsigned int field2 : 2;
unsigned int field3 : 1;
// ...
unsigned int field20 : 1;
// bflag_struct(); <--- Here?
} bflag;
unsigned int integer_member;
Big *pointer_member;
}
Big::Big()
: bflag(), // <--- Can I zero bflag here?
integer_member(0),
pointer_member(NULL)
{
// Or here?
}
Is one of these preferable? Or is there something else I'm missing?
Edit: Based on the accepted answer below (by Ferruccio) I settled on this solution:
class Big {
// ...
struct bflag_struct {
unsigned int field 1 : 1;
// ...
bflag_struct() { memset(this, 0, sizeof *this); };
}
// ...
}
You could always do this in your constructor:
memset(&bflag, 0, sizeof bflag);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With