Enums & enum class in C++
Enumerations name a fixed set of related constants — days, states, error codes — replacing magic numbers with readable, compiler-checked labels. Plain enum leaks its enumerators into the surrounding scope and converts to int silently (Color::Red colliding with Traffic::Red was the classic pain).
enum class (C++11, scoped enums) fixes both: enumerators stay qualified (Color::Red), no implicit int conversion, and the underlying type is customizable (enum class Flags : uint8_t). New code should use enum class essentially always; plain enum survives for bit-flag arithmetic and C compatibility.
Name the set
enum class Day { Mon, Tue, Wed }; creates three named constants — self-documenting alternatives to 0, 1, 2.
Scoped, no leakage
Day::Mon must always be qualified — two enums can both own a value named On without colliding.
No silent int conversion
int x = Day::Mon; fails to compile; static_cast<int>(Day::Mon) converts explicitly when numbering is truly needed.
Pick the storage
enum class Code : uint8_t trims storage to one byte — control layout for protocols and packed structs.
#include <iostream> enum class Traffic { Red, Yellow, Green }; int main() { Traffic light = Traffic::Green; if (light == Traffic::Green) { std::cout << "go" << std::endl; } std::cout << static_cast<int>(Traffic::Red) << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.