C++ Object Class Enumeration
Syntax
enum class EnumerationName {
ValueName1,
ValueName2,
ValueName3,
...
};
Example
#include <iostream>
enum class Color {
red,
orange,
yellow,
green,
blue,
indigo,
violet
};
int main() {
Color myColor = Color::blue;
switch (myColor) {
case Color::red:
std::cout << "My color is red\n";
break;
case Color::orange:
std::cout << "My color is orange\n";
break;
case Color::yellow:
std::cout << "My color is yellow\n";
break;
case Color::green:
std::cout << "My color is green\n";
break;
case Color::blue:
std::cout << "My color is blue\n";
break;
case Color::indigo:
std::cout << "My color is indigo\n";
break;
case Color::violet:
std::cout << "My color is violet\n";
break;
}
return 0;
}
Output
My color is blue
Explanation
An enumeration is a user-defined data type used to assign names to integral constants, the values inside an enumeration are called enumerators. C++ Object Class Enumeration allows you to define an enumeration scoped within a class or namespace.
The enum class
keyword is used to define an enumeration with scoping. Unlike a traditional C++ enumeration, the enumerated values are not implicitly converted to integers or other types, they can be used only with the enum class
name scope.
In the example above, we defined an enumeration named Color
with enumerators red
, orange
, yellow
, green
, blue
, indigo
, and violet
.
We then used a variable named myColor
to store the value Color::blue
, which is an enumerator of the Color
enumeration.
Finally, we used a switch
statement to check the value of myColor
and print the appropriate message.
Use
C++ Object Class Enumeration is used when you want to create a user-defined data type with named values that are mutually exclusive. This allows the code to be more readable and maintainable.
C++ Object Class Enumeration is useful for creating enumerated values that are specific to a class or namespace.
Important Points
enum class
is a new feature from C++11.- Enumerated values are not implicitly converted to integers or other types, they can be used only with the
enum class
name scope. - Enumerated values are mutually exclusive.
- Enumerated values in an enumeration are uniquely named.
Summary
C++ Object Class Enumeration is a user-defined data type used to assign names to integral constants. The enum class
keyword is used to define an enumeration with scoping. Enumerated values in C++ Object Class Enumeration are uniquely named and are mutually exclusive. This allows the code to be more readable and maintainable.