Advertisement
Intermediate C++, Enums & Enum Classes

What are the scoping and name-collision advantages of enum class?

Short answer

With enum class, enumerators live in the enum's scope, so two enums can both have an enumerator named, say, 'None' without clashing (Mode::None vs Color::None). Unscoped enums leak their enumerators into the surrounding scope, causing collisions.

Save C++ mock interview
Advertisement
AModel answer
With enum class, enumerators live in the enum's scope, so two enums can both have an enumerator named, say, 'None' without clashing (Mode::None vs Color::None). Unscoped enums leak their enumerators into the surrounding scope, causing collisions. Scoping is a key reason enum class is preferred.
enum class A { None };
enum class B { None };   // no clash
Real-world example
Two subsystems each define an enumerator 'Error' without conflict because they use enum class.
Likely follow-ups
  • Why do unscoped enums clash? | How does scoping prevent collisions?
Related topics