Class enumerations
An enumeration is a list of all the possible values in a logical collection. C++ enumerations are a great way of, well, enumerating things. For example, if our game uses variables that can only be in a specific range of values, and if those values could logically form a collection or a set, then enumerations are probably appropriate to use. They will make your code clearer and less error-prone. For example, in the switch
example using days of the week, who gets to decide what the first day of the week is? And what if somebody thinks that dayNumber
is something else and does some arithmetic on it? All of a sudden, our day numbering system is a mess. Class enumerations solve this and other problems.
To declare a class enumeration in C++, we use the two keywords enum class
together, followed by the name of the enumeration, followed by the values the enumeration can contain, enclosed in a pair of curly braces, {...}
.
As an example, examine this enumeration declaration...