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

Rule:  PCA#016Checked automatically with code checker

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


Description:

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
}