Enumerated types in C++ give a trivial simulation of symbolic types – that is, objects whose instances have unique, human-readable values. In C++ enumerations are essentially named integers that are either assigned values implicitly by the compiler or explicitly by the programmer (or a combination of both)
C++ enum types inherit their semantics from C with some additions:
- enum objects are now first-class types
- enums may be implicitly converted to integers; but the reverse is not true
Another characteristic illustrated in the above code is the need for all enumerated symbols to be (globally) unique. This can be both frustrating and difficult to maintain for larger systems.
C++11’s enumeration classes provide strongly-typed enumerations.
An enum class, unlike the C++98 enum does not export its enumerator names into its enclosing scope, meaning different enum class objects can have the same enumerator value, without causing a name issue.
Also, enum class values cannot be implicitly converted to integers.
One of the more confusing aspects of C++98 enums was their size – although the type of an enum was defined (int) its size was implementation defined and required only to be a type big enough to hold the largest enumerated value. This means that an enumeration could be 8, 16, 32 or even 64 bits in size; and could change if new enum values were specified. This could (and probably has!) cause alignment issues in embedded systems.
We can now specify the underlying type of the enumeration (as long as it’s an integer type). The default is integer; as with C++98.
If the enum class type is to be used as a forward reference you can (must) provide the underlying type as part of the declaration.
Can’t wait? Download the full set of articles as a PDF, here.
To learn more about Feabhas’ Modern C++ training courses, click here.
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.
He specialises in C++, UML, software modelling, Systems Engineering and process development.