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.
Latest posts by Glennan Carnie (see all)
- Your handy cut-out-and-keep guide to std::forward and std::move - April 26, 2018
- Setting up Sublime Text to build your project - April 12, 2018
- “May Not Meet Developer Expectations” #77 - February 15, 2018