Thursday, February 14, 2019

Enums Vs Enum Classes Pt 1

Enums and enum classes are essentially the same thing, however, using enum classes can avoid a compiler error as well as some other issues that maybe discussed in later posts.

enum AEnum
{
    OK,
    FAILED,
}

enum BEnum
{
    READY,
    FAILED,
}

The above enums will cause a compiler error and this is because within both enums the value FAILED has been declared twice as both values are within a global scope. By using enum classes instead avoids this problem as each value declared is now within its own enum class scope. A enum class is also known as a strongly typed enum. The below code shows the correct usage of enum classes. NB: Enum Classes are available in C++ 11+.

enum class AEnum
{
    OK,
    FAILED,
}

enum class BEnum
{
    READY,
    FAILED,
}

No comments:

Post a Comment