0
0
CppConceptBeginner · 3 min read

What is enum class in C++: Explanation and Example

enum class in C++ is a scoped and strongly typed enumeration that prevents implicit conversions and name conflicts. It improves safety and clarity compared to traditional enums by requiring explicit access to its values.
⚙️

How It Works

Imagine you have a box labeled "Colors" that contains only specific color names. In C++, enum class creates such a box where the names inside are kept separate from other parts of your program. This means you must say exactly which box you mean when you use a color, avoiding confusion.

Unlike old-style enums, which put all names into the same big room (global scope), enum class keeps names inside its own room (scope). Also, it treats these names as special types, so you cannot mix them up with numbers or other enums without asking explicitly. This makes your code safer and easier to understand.

💻

Example

This example shows how to define and use an enum class for colors. Notice how you must use the enum name to access its values.

cpp
#include <iostream>

enum class Color {
    Red,
    Green,
    Blue
};

int main() {
    Color favorite = Color::Green;

    if (favorite == Color::Green) {
        std::cout << "Your favorite color is green!" << std::endl;
    }
    return 0;
}
Output
Your favorite color is green!
🎯

When to Use

Use enum class when you want to group related constant values with clear names and avoid mistakes from mixing them with other numbers or enums. It is especially helpful in large programs where many enums might have overlapping names.

For example, if you have different sets of states like Color and TrafficLight, using enum class keeps their values separate and your code clean. It also helps the compiler catch errors if you try to use the wrong type.

Key Points

  • Scoped: Values are accessed with the enum name, like Color::Red.
  • Strongly typed: No automatic conversion to integers, preventing bugs.
  • Better safety: Compiler checks types strictly.
  • Clearer code: Avoids name clashes in big projects.

Key Takeaways

enum class provides scoped and strongly typed enumerations in C++.
It prevents implicit conversions and name conflicts common in traditional enums.
Use it to write safer and clearer code when grouping related constants.
Access enum values with the enum name to avoid ambiguity.
It helps the compiler catch type errors early.