Skip to content

Latest commit

 

History

History
117 lines (85 loc) · 3.27 KB

File metadata and controls

117 lines (85 loc) · 3.27 KB

Scoped enum


Standard enum

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 declaration

enum class

enum 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 allowed

Rationale: 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_cast must be used
  • enum class == enum struct

enum base

#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;
}

Change the code in ideone.com


enum size

  • Default enum size is sizeof(int)
  • enum underlying type is extended automatically if values greater than int are 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 enum and enum class

enum forward declaration

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;

Exercise

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.