An enum class is a C++11 type-safe enumeration. Prefer class enums over plain enums to minimize surprise [1].
An enum class is a conversion-safe enum:
enum class Color { red , orange }; enum class Fruit { apple, orange }; int main() { Color c = Color::orange; Fruit a = Fruit::orange; Fruit b = Color::orange; //Fails }
Screen output:
Technical note: the code shown is compiled successfully using the G++ 4.4.5 compiler, which is supplied with the Qt Creator 2.0.0 IDE.
- Prefer enum classes to enums [1,2]
- Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 8.5. Advice. page 224: '[6] Prefer class enums over "plain" enums to minimize surprises'
- Scott Meyers. C++ And Beyond 2012 session: 'Initial thoughts on Effective C++11'. 2012. ' Prefer enum classes to enums'