Harwinder Sidhu

New feature in C++11 - "enum class"

Recently, I stumbled upon a new feature in C++11, “enum class”es. A simple feature, but a much need relief. Stroustrup has described the feature briefly in his C++11 FAQ here.

Anyone who has worked with C or C++ knows about enumerations, which was really a half-baked feature in the language. The “old” enumerations had the following problems:

enum BookColor { RED, BLUE, GREEN };
enum PenColor { RED }; // error, RED is already declared
enum BookColor { RED, BLUE, GREEN };
int color = BookColor::RED;   // color = 0 :(
if ( BookColor::RED < 5 )     // perfectly legal with implicit conversion

Enter C++11 “enum class”

enum class BookColor { RED, BLUE, GREEN };
enum class PenColor { RED }; // OK
if ( BookColor::RED > 5 ) // error, not legal in C++11 with enum class
enum class E : unsigned long { E1 = 1, E2 = 2, Ebig = 0xFFFFFFF0U };
// ability to specify an unsigned type for unsigned enum value

Much needed relief

The feature eliminates surprises for new users and ensure type safety, which was missing for so long in C and C++ languages. I guess, I should read the Stroustrup FAQ more often and try to blog everytime I find something new or maybe write something on every topic.

blog comments powered by Disqus