Donald Duck Donald Duck - 22 days ago 6
C++ Question

Can bit fields be used in C++ classes?

In C structs, it is possible to specify another bit length than the default bit length of the type like this:

struct MyStruct{
int myVar : 1; //Size of myVar is 1 bit (so it can take values 0 or 1
int myOtherVar: 4; //Size of myOtherVar is 4 bits (so it can take values 0 to 15)
}


This is called bit fields.

My question is if it is also possible to do this in C++ classes, like this:

class MyClass{
public:
//Some methods
private:
int m_myAttribute : 1;
int m_myOtherAttribute : 4;
}


I searched the web for this but all the examples I found of bit fields used structs, not classes.

I tested this code and it compiled just fine, but I would like to know if the size of the attributes are really the specified size or if the compiler just ignored the bit fields and used the standard
int
size.

Answer

Yes a class can have bitfield members. In C++ there is no difference between a class and a struct except for the default access level. They are both called class types. If you can do something in a struct then you can do that same thing in a class. Since the default access levels are different they will look a little different but you get the same thing. For instance

struct foo
{
    int m_myAttribute : 1;
    int m_myOtherAttribute : 4;
    int m_myOtherOtherAttribute : 27;
};

is the same as

class bar
{
public:
    int m_myAttribute : 1;
    int m_myOtherAttribute : 4;
    int m_myOtherOtherAttribute : 27;
};

Do note though that we had to use public: in the class since by default the mmbers are private.