enum with an example in C++?
enum class was introduced in C++11 to improve the traditional enum. It provides scoped, strongly typed, and name-safe enumerations.
Traditional enum (pre-C++11)
enum Color {
Red,
Green,
Blue
};
Color c = Red; // ✅ Works
int x = Red; // ❌ Allowed (Red is just an int)
void func(int);
void func(char*);
func(0); // Ambiguous: is 0 an int or a null pointer?
func(NULL); // Also ambiguous if NULL is defined as 0
Problems
- No scoping — Red, Green, Blue are in the global scope.
- Implicit conversion to int — which can cause bugs.
- Overlapping names — multiple enums can clash.
enum class — C++11 and later
enum class Color {
Red,
Green,
Blue
};
Color c = Color::Red; // ✅ Must scope with Color::
int x = Color::Red; // ❌ Error: no implicit conversion to int
Can You Convert to int?
Yes, but explicitly:
int x = static_cast<int>(Color::Red); // ✅ OK