16 Enum, Struct, and Union
This chapter introduces three simple kinds of programmer defined data types.
You aren't limited to the compiler provided char, int, double data types and their
derivatives like arrays. You can define your own data types. Most of Part IV of this
text is devoted to various forms of programmer defined type. Here we introduce just
three relatively simple kinds. These are almost the same as the equivalents provided in
C; in contrast, C has no equivalent to the more sophisticated forms of programmer
defined type introduced in Part IV.
Enumerated types, treated in section 16.1, are things that you should find useful in
that they can improve the readability of your programs and they allow the compiler to
do a little extra type checking that can eliminate certain forms of error. Although
useful, enumerated types are not that major a factor in C++ programming.
Structs are the most important of the three language elements introduced here,
section 16.2. They do have wider roles, but here we are interested in their primary role
which is the grouping of related data.
Unions: treat them as a "read only" feature of C++. You will sometimes see unions
being employed in library code that you use, but it is unlikely that you will find any real
application for unions in the programs that you will be writing.
16.1 ENUMERATED TYPES
You often need to use simple integer constants to represent domain specific data. For
example, suppose you needed to represent the colour of an automobile. You could have
const int cRED
const int cBLUE = 1;
Enum, struct, and union
auto_colour = cBLUE;
This is quite workable. But there are no checks. Since variable auto_colour is an
integer, the following assignments are valid:
auto_colour = -1;
auto_colour = rand();
But of course, these statements lose the semantics; variable auto_colour doesn't any
longer represent a colour, it is just an integer.
It is nice to be able to tell the compiler:
"Variable auto_colour is suppose