Bitesize Modern C++: enum class

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

image

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.

image

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.

image

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.

image

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.

Glennan Carnie
Dislike (0)
Website | + posts

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.

About Glennan Carnie

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.
This entry was posted in C/C++ Programming and tagged , , , , , , . Bookmark the permalink.

1 Response to Bitesize Modern C++: enum class

  1. 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

    Like (0)
    Dislike (0)

Leave a Reply