29. Enumerations – Modern C++ for Absolute Beginners: A Friendly Introduction to C++ Programming Language and C++11 to C++20 Standards

© Slobodan Dmitrović 2020
S. DmitrovićModern C++ for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-6047-0_29

29. Enumerations

Slobodan Dmitrović1 
(1)
Belgrade, Serbia
 

Enumeration, or enum for short, is a type whose values are user-defined named constants called enumerators.

There are two kinds of enums: the unscoped enums and scoped enums. The unscoped enum type can be defined with:
enum MyEnum
{
    myfirstvalue,
    mysecondvalue,
    mythirdvalue
};
To declare a variable of enumeration type MyEnum we write:
enum MyEnum
{
    myfirstvalue,
    mysecondvalue,
    mythirdvalue
};
int main()
{
    MyEnum myenum = myfirstvalue;
    myenum = mysecondvalue; // we can change the value of our enum object
}
Each enumerator has a value of underlying type. We can change those:
enum MyEnum
{
    myfirstvalue = 10,
    mysecondvalue,
    mythirdvalue
};
These unscoped enums have their enumerators leak into an outside scope, the scope in which the enum type itself is defined. Old enums are best avoided. Prefer scoped enums to these old-school, unscoped enums. Scoped enums do not leak their enumerators into an outer scope and are not implicitly convertible to other types. To define a scoped enum, we write:
enum class MyEnum
{
    myfirstvalue,
    mysecondvalue,
    mythirdvalue
};
To declare a variable of type enum class (scoped enum) we write:
enum class MyEnum
{
    myfirstvalue,
    mysecondvalue,
    mythirdvalue
};
int main()
{
    MyEnum myenum = MyEnum::myfirstvalue;
}

To access an enumerator value, we prepend the enumerator with the enum name and a scope resolution operator :: such as MyEnum::myfirstvalue, MyEnum:: mysecondvalue, etc.

With these enums, the enumerator names are defined only within the enum internal scope and implicitly convert to underlying types. We can specify the underlying type for scoped enum:
enum class MyCharEnum : char
{
    myfirstvalue,
    mysecondvalue,
    mythirdvalue
};
We can also change the initial underlying values of enumerators by specifying the value:
enum class MyEnum
{
    myfirstvalue = 15,
    mysecondvalue,
    mythirdvalue = 30
};

Summary: prefer enum class enumerations (scoped enums) to old plain unscoped enums. Use enumerations when our object is to have one value out of a set of predefined named values.