Enums in C++
A short note on C++11 enum class: scoped names, a fixed underlying type, no implicit int conversion, plus using enum and std::to_underlying.
Here is the short note
enum class EnumName : char { ValueA = 'a', ValueB, ValueC };
Enum class (a scoped enum, since C++11) is a new type. It is, of course, an enum, but its names live in their own scope, like a namespace. So you write EnumName::ValueA, not just ValueA, and the names don’t leak into the surrounding code.
The part after the colon is the underlying type, char in here. The value of ValueA is declared as 'a', so ValueB becomes 'b' and ValueC becomes 'c'. Note that it has to be a character literal 'a', not a string "a"; a string doesn’t compile.
The other big difference from the old enum is that there is no implicit conversion to an integer. You have to cast it yourself:
#include <iostream>
#include <utility>
enum class EnumName : char { ValueA = 'a', ValueB, ValueC };
int main()
{
EnumName e = EnumName::ValueB;
// int i = e; // error, no implicit conversion
char c = static_cast<char>(e); // ok
std::cout << c << "\n"; // prints b
// C++23
std::cout << std::to_underlying(EnumName::ValueC) << "\n"; // prints c
}
Update (2026): C++20 added
using enum EnumName;, which brings the names into the current scope. It is handy inside aswitch, so you can writecase ValueA:instead ofcase EnumName::ValueA:. C++23 addedstd::to_underlyingin<utility>, which is a cleaner way to do thestatic_castabove.