Advertisement
Intermediate C++, Enums & Enum Classes

How do you specify the underlying type of an enum?

Short answer

You can specify the integer type backing an enum with a colon: enum class Flag : std::uint8_t { ... }. This controls the size and range, useful for memory layout, serialization, and interoperability.

Save C++ mock interview
Advertisement
AModel answer
You can specify the integer type backing an enum with a colon: enum class Flag : std::uint8_t { ... }. This controls the size and range, useful for memory layout, serialization, and interoperability. Scoped enums default to int; specifying the type also allows forward declaration.
enum class Flag : std::uint8_t { A = 1, B = 2, C = 4 };
Real-world example
A protocol enum uses uint8_t as its underlying type to match a one-byte wire field.
Likely follow-ups
  • Why control the underlying type? | What is the default for enum class?
Related topics