TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
C++ Coding Standard

Rule:  PCA#016Checked automatically with code checker

Synopsis:Use enum classes instead of old-style enums
Severity Level:7
Category:Parts of C++ to Avoid


Old-style C++ enums are essentially integers; they could be compared with integers or with other enums of different types without getting compilation errors. Most of the times this is not intentional. Now with strongly typed enums, the compiler will not accept this any more. If really needed, you can always use a typecast.

Another limitation of old-style enum values is that they are unscoped--in other words, you couldn't have two enumerations that shared the same name:

// this code won't compile because both enums contain BLUE!
enum Color {RED, GREEN, BLUE}; 
enum Feelings {EXCITED, MOODY, BLUE};

This in contrast with enum classes:

// this code will compile (if your compiler supports C++11 strongly typed enums)
enum class Color {RED, GREEN, BLUE}; 
enum class Feelings {EXCITED, MOODY, BLUE};

The use of the word class is meant to indicate that each enum type really is different and not comparable to other enum types. Strongly typed enums, enum classes, also have better scoping. Each enum value is scoped within the name of the enum class. In other words, to access the enum values, you must write:

Color color = Color::GREEN;
if ( Color::RED == color )
    // the color is red

Yet another advantage of enum classes is that it is possible to specify the underlying type (that is: the byte size), which is very useful when using this enum declaration in definition of network protocols or other binary data. Otherwise the size of the enum is compiler dependent (usually machine word size), which is not portable. Example:

enum class Permissions : unsigned short {Readable = 0x4, Writable = 0x2, Executable = 0x1};