studentis declared on lines 9–28. Although this is a trivial class, it is interesting
because all the data is packed into five bits on lines 24–27. The first bit on line 24 repre-
sents the student’s status, full-time or part-time. The second bit on line 25 represents
whether this is an undergraduate. The third bit on line 25 represents whether the student
lives in a dorm. The final two bits represent the four possible food plans.
The class methods are written as for any other class and are in no way affected by the
fact that these are bit fields and not integers or enumerated types.
The member function GetStatus()on lines 30–36 reads the Boolean bit and returns an
enumerated type, but this is not necessary. It could just as easily have been written to
return the value of the bit field directly. The compiler would have done the translation.
To prove that to yourself, replace the GetStatus()implementation with this code:
STATUS student::GetStatus()
{
return myStatus;
}
No change whatsoever should occur in the functioning of the program. It is a matter of
clarity when reading the code; the compiler isn’t particular.
Note that the code on line 47 must check the status and then print the meaningful mes-
sage. It is tempting to write this:
cout << “Jim is “ << Jim.GetStatus() << endl;
that simply prints this:
Jim is 0
The compiler has no way to translate the enumerated constant PartTimeinto meaningful
text.
On line 62, the program switches on the food plan, and for each possible value, it puts a
reasonable message into the buffer, which is then printed on line 71. Note again that the
switchstatement could have been written as follows:
case 0: strcpy(Plan,”One meal”); break;
case 1: strcpy(Plan,”All meals”); break;
case 2: strcpy(Plan,”Weekend meals”); break;
case 3: strcpy(Plan,”No Meals”);break;
The most important thing about using bit fields is that the client of the class need not
worry about the data storage implementation. Because the bit fields are private, you can
feel free to change them later and the interface will not need to change.
778 Day 21