Default Member Initializers for Bit Fields
Learn how to default initialize the members of a bit field with an example.
We'll cover the following...
First of all, what is a bit field? Here is the definition from Wikipedia: “A bit field is a data structure used in computer programming. It consists of a number of adjacent computer memory locations which have been allocated to hold a sequence of bits, stored so that any single bit or group of bits within the set can be addressed. A bit field is most commonly used to represent integral types of known, fixed bit-width.”
With C++20, we can default initialize the members of a bit field:
Press + to interact
#include<iostream>struct Class11 {int i = 1;int j = 2;int k = 3;int l = 4;int m = 5;int n = 6;};struct BitField20 {int i : 3 = 1;int j : 4 = 2;int k : 5 = 3;int l : 6 = 4;int m : 7 = 5;int n : 7 = 6;};int main() {std::cout << '\n';std:: cout << "sizeof(Class11): " << sizeof(Class11) << '\n';std:: cout << "sizeof(BitField20): " << sizeof(Class11) << '\n';std::cout << '\n';}
According to the members of a class (lines 4 - 9) with C++11, the members of the bit field can have default initializers (lines 13 - 18) with C++20. When you sum up the numbers ...