The C++11's scoped enum (enum class
) are better than the conventional enum because they do not cause name clashes and are strongly typed. Enum got another change in C++11, which applies to both scoped and conventional enum, that they can have a specified integral underlying type.
This is how scoped enum are declared as opposed to plain conventional enum:
// Scoped
enum class Colors { Red, Green, Blue };
enum class Weekdays : unsigned char { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
// Conventional
enum Assets { Equity, Bond, Future };
enum Animals : short { Cat, Lion, Tiger, Bear };
The only syntactic difference between the declaration of the two is the use of keyword class
with scoped enum. Note that the underlying integral type can be specified for both scoped as well as conventional enum.
Look at the following example code that uses above 4 enum and tell which lines would not compile.
Colors color = Colors::Blue;
int x = color;
int y = Equity;
if( y == Cat ) std::cout << "True";
if(Colors::Blue == Weekdays::Sun) std::cout << "True";
int z = Bond;
Check all those lines that would not compile: