Why is enum class preferred over plain enum?

c++ enum class to int
c++ enum class to string
enum class vs enum
c++ enum class methods
enum class c#
enum class java
enum class python
enum class kotlin

I heard a few people recommending to use enum classes in C++ because of their type safety.

But what does that really mean?


Why is enum class preferred over plain enum?, 3: Prefer enum class es over “plain” enum s. The enumerators of a scoped enum (enum class) will not automatically convert to int. You have to  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.


C++ Core Guidelines: Rules for Enumerations, Enum Classes in C++ and Their Advantage over Enum DataType Below are some of the reasons as to what are the limitations of Enum Type and why we File Handling through C++ Classes · “static const” vs “#define” vs “enum” · C++  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more Why am I getting no warning for enum comparison mismatch?


The basic advantage of using enum class over normal enums is that you may have same enum variables for 2 different enums and still can resolve them(which has been mentioned as type safe by OP)

For eg:

enum class Color1 { red, green, blue };    //this will compile
enum class Color2 { red, green, blue };

enum Color1 { red, green, blue };    //this will not compile 
enum Color2 { red, green, blue };

As for the basic enums, compiler will not be able to distinguish whether red is refering to the type Color1 or Color2 as in hte below statement.

enum Color1 { red, green, blue };   
enum Color2 { red, green, blue };
int x = red;    //Compile time error(which red are you refering to??)

Enum Classes in C++ and Their Advantage over Enum DataType , Traditional enum ("plain enum", "old style enum"); enum class es also commonly referred to as scoped enum s. Example declaring a traditional  switch blocks won't work with an enum-as-class. User empi mentioned the similarity of the above enum-as-class sample to Java enums. It seems that in the Java world, there is a recognised pattern called the Typesafe Enum; apparently this pattern goes back to Joshua Bloch's book Effective Java.


Enumerations are used to represent a set of integer values.

The class keyword after the enum specifies that the enumeration is strongly typed and its enumerators are scoped. This way enum classes prevents accidental misuse of constants.

For Example:

enum class Animal{Dog, Cat, Tiger};
enum class Pets{Dog, Parrot};

Here we can not mix Animal and Pets values.

Animal a = Dog;       // Error: which DOG?    
Animal a = Pets::Dog  // Pets::Dog is not an Animal

Prefer C++ "enum class" to "enum" · Issue #1049 , Before C++11, all enums were just, basically, integers. And you could use them like that. It made it too easy to give bad values to functions  Just put MyEnum in its own file. If you decide to delete Class1, your enum will still be there! Deleting the class and deleting the file the class is in are two different things. Even if you put them in the same file at first, you can always move MyEnum to another file and delete the original file later.


C++11 FAQ mentions below points:

conventional enums implicitly convert to int, causing errors when someone does not want an enumeration to act as an integer.

enum color
{
    Red,
    Green,
    Yellow
};

enum class NewColor
{
    Red_1,
    Green_1,
    Yellow_1
};

int main()
{
    //! Implicit conversion is possible
    int i = Red;

    //! Need enum class name followed by access specifier. Ex: NewColor::Red_1
    int j = Red_1; // error C2065: 'Red_1': undeclared identifier

    //! Implicit converison is not possible. Solution Ex: int k = (int)NewColor::Red_1;
    int k = NewColor::Red_1; // error C2440: 'initializing': cannot convert from 'NewColor' to 'int'

    return 0;
}

conventional enums export their enumerators to the surrounding scope, causing name clashes.

// Header.h

enum vehicle
{
    Car,
    Bus,
    Bike,
    Autorickshow
};

enum FourWheeler
{
    Car,        // error C2365: 'Car': redefinition; previous definition was 'enumerator'
    SmallBus
};

enum class Editor
{
    vim,
    eclipes,
    VisualStudio
};

enum class CppEditor
{
    eclipes,       // No error of redefinitions
    VisualStudio,  // No error of redefinitions
    QtCreator
};

The underlying type of an enum cannot be specified, causing confusion, compatibility problems, and makes forward declaration impossible.

// Header1.h
#include <iostream>

using namespace std;

enum class Port : unsigned char; // Forward declare

class MyClass
{
public:
    void PrintPort(enum class Port p);
};

void MyClass::PrintPort(enum class Port p)
{
    cout << (int)p << endl;
}

.

// Header.h
enum class Port : unsigned char // Declare enum type explicitly
{
    PORT_1 = 0x01,
    PORT_2 = 0x02,
    PORT_3 = 0x04
};

.

// Source.cpp
#include "Header1.h"
#include "Header.h"

using namespace std;
int main()
{
    MyClass m;
    m.PrintPort(Port::PORT_1);

    return 0;
}

Enumerations in C/C++ (traditional enum vs enum class) Part 1 , Standard enum / plain enum / unscoped enum / conventional enum; Strong enum / enum class / scoped enum / new enum / managed enum. Enum classes have another advantages over old-style enums. You can have a forward declaration to a strongly typed enum, meaning that you can write code like: enum class Mood; void assessMood (Mood m); // later on: enum class Mood { EXCITED, MOODY, BLUE }; Why would this be useful? Forward declarations are often about the physical layout of code on disk into different files or to provide opaque objects as part of an API.


Enum vs enum class C++11 - C++ Forum, Note: an explicit specialization declaration of a scoped enumeration member of a class template c++ - Why is enum class preferred over plain enum? - Stack . The enum classes ("new enums", "strong enums") address three problems with traditional C++ enumerations: conventional enums implicitly convert to int, causing errors when someone does not want an enumeration to act as an integer. conventional enums export their enumerators to the surrounding scope, causing name clashes.


Scoped vs. unscoped enum, c++ - Why is enum class preferred over plain enum? - Stack stackoverflow.com. The new enums are "enum class" because they combine aspects of traditional. If you want the enumerator names to be hidden then you can use the c++11 scoped enum feature, i.e. this compiles fine (notice the class keyword after enum): enum class StiffnessModel Seed = 1,


Web - enum class cpp, The example for Enum.4 displays a technique of overloading the ++ operator to increment an int-based enum. This comes directly after Enum.3 which states that one should "Prefer class enums over 'plain' enums" and is the only example in the Enum guidelines to do so.