Enum Class
Choose enum class over enum for type safety.
1. Overview
Enum class is introduced in C++11. Compared to traditional Enum, it shows differences in:
- Scope
- Underlying types
- Type safety
- Enum constants
2. Scope
- enum defines an enumeration in the global scope, enum values are directly accessible without any scope qualification, meaning its enumerators can potentially clash with other names in the same scope.
- enum class introduces scoped enumerations. Enumerators inside an enum class are scoped to the enumeration, reducing the risk of naming conflicts.
1 | enum class Color { |
3. Underlying types
- By default, enum uses int as the underlying type for its enumerators. This can lead to unintended conversions and comparison issues.
- enum class requires an explicitly specified underlying type, preventing implicit conversions and providing stronger type safety.
1 | enum Color1 { |
4. Type safety
- enum does not provide strong type safety. Enumerators are implicitly convertible to integers and can lead to unintended behavior.
- enum class enhances type safety by encapsulating enumerators within the scope of the enumeration. Enumerators are not implicitly convertible to integers, reducing potential bugs.
1 | enum class Color { |
5. Enum constants
- enum constants can be defined with any valid integer value, including duplicates and values outside the declared range.
- enum class constants are strongly enforced to be unique within the scope and adhere to the underlying type’s range.
References
Enum Class