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.
More information
Can’t wait? Download the full set of articles as a PDF, here.
To learn more about Feabhas’ Modern C++ training courses, click here.
- Practice makes perfect, part 3 – Idiomatic kata - February 27, 2020
- Practice makes perfect, part 2– foundation kata - February 13, 2020
- Practice makes perfect, part 1 – Code kata - January 30, 2020
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.
Won't the definition of the two C++98 enums cause a compilation error when they both define a common symbol (ODR), before even creating a confusion as to which GOLD we mean ? A minimal example here https://coliru.stacked-crooked.com/a/3f8433eb8b8aac6d