I heard a few people recommending to use enum classes in C++ because of their type safety.
But what does that really mean?
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
C++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped. Class enum doesn't allow implicit conversion to int, and also doesn't compare enumerators from different enumerations. To define enum class we use class keyword after enum keyword.
An enumeration is a user-defined type that consists of a set of named integral constants that are known as enumerators. This article covers the ISO Standard C++ Language enum type and the scoped (or strongly-typed) enum class type which is introduced in C++11.
Some of the advantages of enum are:It can be used in switch case. It improves type safety. It can have fields, constructors and methods. It can implement many interfaces but cannot extend any class.
C++ has two kinds of enum
:
enum class
esenum
sHere are a couple of examples on how to declare them:
enum class Color { red, green, blue }; // enum class enum Animal { dog, cat, bird, human }; // plain enum
What is the difference between the two?
enum class
es - enumerator names are local to the enum and their values do not implicitly convert to other types (like another enum
or int
)
Plain enum
s - where enumerator names are in the same scope as the enum and their values implicitly convert to integers and other types
Example:
enum Color { red, green, blue }; // plain enum enum Card { red_card, green_card, yellow_card }; // another plain enum enum class Animal { dog, deer, cat, bird, human }; // enum class enum class Mammal { kangaroo, deer, human }; // another enum class void fun() { // examples of bad use of plain enums: Color color = Color::red; Card card = Card::green_card; int num = color; // no problem if (color == Card::red_card) // no problem (bad) cout << "bad" << endl; if (card == Color::green) // no problem (bad) cout << "bad" << endl; // examples of good use of enum classes (safe) Animal a = Animal::deer; Mammal m = Mammal::deer; int num2 = a; // error if (m == a) // error (good) cout << "bad" << endl; if (a == Mammal::deer) // error (good) cout << "bad" << endl; }
enum class
es should be preferred because they cause fewer surprises that could potentially lead to bugs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With