C’s enumerations
are fairly primitive, simply
associating integral values with names, but they provide no type checking. In
C++, as you may have come to expect by now, the concept of type is fundamental,
and this is true with enumerations. When you create a named enumeration, you
effectively create a new type just as you do with a class: The name of your
enumeration becomes a reserved word for the duration of that translation unit.
In addition, there’s stricter type
checking for enumerations in C++ than in C. You’ll notice this in
particular if you have an instance of an enumeration
color called a. In C
you can say a++, but in C++ you can’t. This is because incrementing
an enumeration is performing two type conversions, one of them legal in C++ and
one of them illegal. First, the value of the enumeration is implicitly cast from
a color to an int, then the value is incremented, then the
int is cast back into a color. In C++ this isn’t allowed,
because color is a distinct type and not equivalent to an int.
This makes sense, because how do you know the increment of blue will even
be in the list of colors? If you want to increment a color, then it
should be a class (with an increment operation) and not an enum, because
the class can be made to be much safer. Any time you write code that assumes an
implicit conversion to an enum type, the compiler will flag this
inherently dangerous activity.