Advertisement
Beginner C++, Enums & Enum Classes

What is an enum class (scoped enum) and why is it preferred?

Short answer

An enum class (scoped enumeration, C++11) scopes its enumerators to the enum's name (Color::Red) and does not implicitly convert to int, preventing accidental mixing with numbers or other enums.

Save C++ mock interview
Advertisement
AModel answer
An enum class (scoped enumeration, C++11) scopes its enumerators to the enum's name (Color::Red) and does not implicitly convert to int, preventing accidental mixing with numbers or other enums. This gives stronger type safety and avoids name clashes, so enum class is preferred over plain enum in modern code.
enum class Color { Red, Green, Blue };
Color c = Color::Red;
// int x = c;   // error: no implicit conversion
Real-world example
Using enum class for Status and Priority prevents accidentally comparing a Status to a Priority.
Likely follow-ups
  • How does it improve type safety? | Why must you qualify the enumerators?
Related topics