Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

    // ...
}
like image 424
Ben Martin Avatar asked Mar 04 '09 20:03

Ben Martin


1 Answers

You could always do this in your constructor:

memset(&bflag, 0, sizeof bflag);
like image 142
Ferruccio Avatar answered Oct 07 '22 07:10

Ferruccio