Skip to content

Latest commit

 

History

History
117 lines (69 loc) · 2.09 KB

CppEnumClass.md

File metadata and controls

117 lines (69 loc) · 2.09 KB

 

 

 

 

 

 

An enum class is a C++11 type-safe enumeration. Prefer class enums over plain enums to minimize surprise [1].

 

 

 

 

Example

 

 

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:

 


cannot convert 'Color' to 'Fruit' in initialization

 

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.

 

 

 

 

 

 

 

 

 

 

 

 

  1. 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'
  2. Scott Meyers. C++ And Beyond 2012 session: 'Initial thoughts on Effective C++11'. 2012. ' Prefer enum classes to enums'