Yes a class
can have bitfield elements. In C ++, there is no difference between class
and a struct
, with the exception of the default access level and the default inheritance type. They are called class types. If you can do something in a struct
, then you can do the same in a class
. Since the default access levels are different, they will look a little different, but you will get the same. For instance,
struct foo { int m_myAttribute : 1; int m_myOtherAttribute : 4; int m_myOtherOtherAttribute : 27; };
coincides with
class bar { public: int m_myAttribute : 1; int m_myOtherAttribute : 4; int m_myOtherOtherAttribute : 27; };
Note that we had to use public:
in the class, because by default the members are private.
Now about the size of bit fields in C ++. [class.bit] / 1 has all the necessary information:
A constant expression must be an integral constant expression with a value greater than or equal to zero. The value of the expression of the integral constant may be greater than the number of bits in the object representation (3.9) of the type of bit fields; in such cases, the extra bits are used as padding bits and do not participate in the representation of the values ββ(3.9) of the bit field. The distribution of bit fields within a class object is determined by the implementation. The alignment of bit fields is determined by the implementation. Bit fields are packed into some address distribution unit. [Note: bit fields highlight allocation units on some machines, not others. Bit fields are assigned from right to left on some machines, from left to right on others. -end note]
my accent
From this we get that the size of the bit-feild will be at least the size of the underlying data type, but if you redistribute the space, then this additional space turns into a padding and is not used for the value of the bit member of the field.
source share