0Pricing
C++ Academy · Lesson

Scoped enum class

Type-safe enumerations.

Plain Enums Leak Names

A classic C-style enum dumps its names into the surrounding scope and silently converts to int. That makes name clashes and accidental comparisons easy.

  • enum class fixes both problems.
  • Values are scoped and strongly typed.
#include <iostream>
enum Color { Red, Green, Blue };
int main() {
    Color c = Green;
    int x = c; // implicit conversion to int
    std::cout << x << "\n";
}

Declaring a Scoped Enum

Add the class (or struct) keyword to make a scoped enumeration. Now you must qualify each value with the enum name.

#include <iostream>
enum class Color { Red, Green, Blue };
int main() {
    Color c = Color::Green;
    if (c == Color::Green) std::cout << "green\n";
}

All lessons in this course

  1. Scoped enum class
  2. Unions and Their Risks
  3. std::variant
  4. std::visit
← Back to C++ Academy