What is the best way to initialize a bitfield struct in C++?

Ben Martin picture Ben Martin · Mar 4, 2009 · Viewed 11.5k times · Source

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:

  1. Create a constructor in the bitfield
  2. Zero out in the initializer list of the constructor for the containing class
  3. Zero out in the body of the constructor for the containing class

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); };
    }

    // ...
}

Answer

Ferruccio picture Ferruccio · Mar 4, 2009

You could always do this in your constructor:

memset(&bflag, 0, sizeof bflag);