In C++, enum
and enum class
are used to define enumerations, which are user-defined data types that represent a set of named integer constants.
The main difference between enum
and enum class
is in how the underlying constants are scoped:
enum
: The constants defined in an enum
are placed in the outer scope, which means that they can potentially clash with other names in the same scope. For example:
enum Color {
RED,
GREEN,
BLUE
};
int RED = 0; // this will cause a compilation error
enum class
: The constants defined in an enum class
are scoped within the enumeration itself, which means that they cannot clash with other names in the same scope. For example:
enum class Color {
RED,
GREEN,
BLUE
};
int RED = 0; // this is allowed
Another difference between enum
and enum class
is in how the underlying constants are implicitly converted to integers:
enum
: The constants defined in an enum
are implicitly converted to integers, which means that they can be used interchangeably with integers. For example:
enum Color {
RED,
GREEN,
BLUE
};
int redValue = RED; // this is allowed
int blueValue = BLUE; // this is allowed
enum class
: The constants defined in an enum class
are not implicitly converted to integers, which means that they cannot be used interchangeably with integers. For example:
enum class Color {
RED,
GREEN,
BLUE
};
int redValue = Color::RED; // this is not allowed
int blueValue = static_cast<int>(Color::BLUE); // this is allowed with explicit conversion
To summarize, enum class
provides better scoping and type safety compared to enum
, but requires explicit casting to convert the enum constants to integers.
Here's an example of how to declare and use an enum class
in C++:
enum class Color {
RED,
GREEN,
BLUE
};
int main() {
Color myColor = Color::RED; // declare a variable of type Color and assign it the value Color::RED
switch (myColor) {
case Color::RED:
std::cout << "The color is red." << std::endl;
break;
case Color::GREEN:
std::cout << "The color is green." << std::endl;
break;
case Color::BLUE:
std::cout << "The color is blue." << std::endl;
break;
default:
std::cout << "Invalid color." << std::endl;
break;
}
return 0;
}
In this example, we define an enum class
called Color
that contains three named constants: RED
, GREEN
, and BLUE
. We then declare a variable myColor
of type Color
and assign it the value Color::RED
. We use a switch
statement to check the value of myColor
and print a message depending on the color.
Note that we use the scope resolution operator ::
to access the named constants in the enum class
. Also note that since the values in an enum class
are not implicitly converted to integers, we must use the name of the enum class
and the named constant to refer to the values.