enum Colors {
RED = 10,
ORANGE,
GREEN
};
Colors a = RED; // OK
int b = GREEN; // OK
enum Fruits {
ORANGE,
BANANA
};
Colors c = ORANGE; // 11 or 0?
// Hopefully: error: ‘ORANGE’ conflicts with a previous declarationenum class Languages {
ENGLISH,
GERMAN,
POLISH
};
Languages a = Languages::ENGLISH;
// Languages b = GERMAN;
// int c = Languages::ENGLISH;
int d = static_cast<int>(Languages::ENGLISH); // only explicit cast allowedRationale: Stronger and less error-prone enumeration types.
- Introduced in C++11
- Restricts range of defined constants only to those defined in an enum class
- Enum values must be accessed with the enum name scope
-
Does not allow implicit conversions,
static_castmust be used -
enum class == enum struct
#include <iostream>
#include <limits>
enum Colors { YELLOW = 10, ORANGE };
enum BigValue { VALUE = std::numeric_limits<long>::max() };
enum RgbColors : unsigned char {
RED = 0x01,
GREEN = 0x02,
BLUE = 0x04,
// BLACK = 0xFF + 1 // error: enumerator value 256 is outside
}; // the range of underlying type ‘unsigned char’
int main() {
std::cout << sizeof(Colors) << std::endl; // 4 - sizeof(int)
std::cout << sizeof(BigValue) << std::endl; // 8 - sizeof(long)
std::cout << sizeof(RgbColors) << std::endl; // 1 - sizeof(unsigned char)
return 0;
}-
Default enum size is
sizeof(int) -
enumunderlying type is extended automatically if values greater thanintare provided - To save some memory we can define the underlying type using inheritance
- A compiler will not allow defining value greater than the defined base can hold
-
Inheritance work on both
enumandenum class
For enums with the defined underlying type, it is possible to provide only a forward declaration, if values do not need to be known.
There will be no need to recompile source file if new enum values are added.
enum Colors : unsigned int;
enum struct Languages : unsigned char;Write a new scoped enum named Color and define in it 3 colors of your choice.
Inherit from unsigned char.
Add a new field: Color color in the Shape class, so that every shape can have its own defined color.
Add a default color value in a Shape class.