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