top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why we prefer enum class over plain enums in C++?

+2 votes
688 views
Why we prefer enum class over plain enums in C++?
posted Nov 14, 2013 by Deepak Dasgupta

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Due to data hiding feature of C++. But I am not sure.

1 Answer

+1 vote
 
Best answer
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

1. Enum Classes - enumerator names are local to the enum and their values do not implicitly convert to other types (like another enum or int)
2. Plain Enums - where enumerator names are in the same scope as the enum and their values implicitly convert to integers and other types

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;
}

So, Enum classes should be preferred because they cause fewer surprises that could potentially lead to bugs.

answer Nov 18, 2013 by Satyabrata Mahapatra
Similar Questions
0 votes

While doing design for a software, what things enforce to use template classes and template functions ?
Is it consider best practices or not ?

...