Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) enum class

 

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.

 

 

 

 

 

Advice

 

 

 

 

 

 

References

 

  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'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict