3

What is the difference between the Enum and Enum Class and how to converting Enum value to the integer in "Enum" and "Enum Class"?

3
  • 1
    Does this answer your question? Getting the integer value from enum Commented Jan 11, 2021 at 11:25
  • 1
    @RolandasUlevicius No, that question is about C# enums. Commented Jan 11, 2021 at 11:29
  • 1
    No, my question is about difference between enum value and enum class value in c++. Commented Jan 11, 2021 at 11:29

2 Answers 2

5

C++ has two kinds of enum:

enum classes
Plain enums
Here 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 classes - enumerator names are local to the enum and their values do not implicitly convert to other types (like another enum or int)

Plain enums - where enumerator names are in the same scope as the enum and their values implicitly convert to integers and other types

in the Enum:

enum type{x=10, y, z=50, j};

int value = x;

in the Enum Class:

enum class type{x=10, y, z=50, j};

int value = static_cast<int>(type::x);
Sign up to request clarification or add additional context in comments.

2 Comments

The second example should be int value= static_cast<int>(type::x);
Note that the underlying type defaults to int in 'scoped enumerations', unless otherwise specified explicitly such as enum class myEnum: int64_t {...}. See the ref.
2

As of C++23 there's a library function, std::to_underlying, for converting enum class values to their underlying value.

int main ()
{
    enum class Foo {a, b, c, d, e, f};

    return std::to_underlying(Foo::f); // returns 5
}

https://godbolt.org/z/PE35eq78j

https://en.cppreference.com/w/cpp/utility/to_underlying

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.