Coupon Accepted Successfully!


Bit Fields and Classes

Bit field provides exact amount of bits required for storage of values. If a variable value is 1 or 0 we need a single bit to store it. In the same way, if the variable is expressed between 0 and 3, then the two bits are sufficient for storing these values. Similarly if a variable assumes values between 0 and 7, then three bits will be enough to hold the variable and so on. The number of bits required for a variable is specified by non-negative integer followed by a colon.

To hold the information, we use the variables. The variables occupy minimum one byte for char and two bytes for integer. Instead of using complete integer if bits are used, memory space can be saved. For example, to know the information about the vehicles, following information has to be stored in the memory:


In order to store the status of the above information, we may need two bits for the type of fuel as to whether the vehicle is of petrol or diesel type, three bits for its type as to whether the vehicle is two- or four-wheeler, and similarly, three bits for the model of the vehicle. Total bits required for storing the information would be 8 bits, that is one byte. It means that the total information can be packed into a single byte. Eventually bit fields are used for conserving the memory. The amount of memory saved by using bit fields will be substantial which is proved from the above example.

However, there are restrictions on bit fields when arrays are used. Arrays of bit fields are not permitted. Also the pointer cannot be used for addressing the bit field directly, although the use of the member access operator (->) is acceptable. The unnamed bit fields could be used for padding as well as for alignment purposes.

  1. Bits fields should have integral type. A pointer and array type is now allowed.
  2. Address of bit fields cannot be obtained using & operator.

The class for the above problem would be as follows:

The colon (:) in the above declaration tells to the compiler that bit fields are used in the class and the number after it indicates how many bits are required to allot for the field. A simple program is illustrated as follows:

8.41 Write a program to use bit fields with classes and display the contents of the bit fields.

Explanation: In the above program, using #define macros are declared. The information about the vehicle is indicated with integers from 1 to 6. The class vehicle is declared with bit fields. The number of bits required for each member is initialized. As per the program, type of vehicle requires 3 bits, fuel requires 2 bits, and model requires 3 bits. An object v is declared. The constructor initializes bits fields with data. The output of the program displays integer value stored in the bit fields, which can be verified with macro definitions initialized at the beginning of the program.

Test Your Skills Now!
Take a Quiz now
Reviewer Name