What is the difference between an enum and an enum class (scoped enumeration)?
Last updated
A scoped enumeration (enum class) fixes the safety problems of a plain enum: it doesn't leak its enumerators into the surrounding scope and doesn't implicitly convert to integers.
Scope of enumerators: Plain
enumnames go into the enclosing scope, risking name clashes;enum classnames are accessed asColor::Red.Implicit conversion: A plain
enumconverts silently toint(error-prone in comparisons/arithmetic); a scoped enum requires an explicitstatic_cast.Underlying type: Both can specify it (e.g.
enum class E : std::uint8_t); scoped enums default toint, giving predictable size and forward declaration.Rule of thumb: prefer
enum classby default for type safety; use plainenumonly for legacy/bit-flag interop convenience.
[lang:cpp]
enum class Color { Red, Green };
Color c = Color::Red;
// int x = c; // error: no implicit conversion
int x = static_cast<int>(c); // explicit, intentional