default: each enumerator is mapped to a whole number from 0 to N-1
enum classday { mon, tue, wed, thu, fri, sat, sun }; day d = day::mon; d = day::tue; // RIGHT! d = wed; // WRONG! COMPILER ERROR: 'wed' only known in day's scope
enumerators confined to a named scope
cannot query properties of enumeration as in some other languages
enumday { mon, tue, wed, thu, fri, sat, sun }; day d = mon; // OK!, enumerator "mon" unscoped int i = wed; // OK!, i = 2 enumstars { sun, … }; // WRONG! COMPILER ERROR: name collision
enumerators not confined to a scope ⇒ name collisions
dangerous implicit conversion to underlying type
cannot query properties of enumeration as in some other languages
avoid unscoped enumerations
Underlying Type Of Enumerations
must be an integer type (char, short, long, …)
int is the default
// 7 values ⇒ char should be enough enum classday : char { mon, tue, wed, thu, fri, sat, sun }; // less than 10,000 ⇒ short should be enough enum classlanguage_ISO639 : short { abk, aar, afr, aka, amh, ara, arg, … };
Custom Enumerator Mapping
enumerator values can be set explicitly
need not start with 0
some values can be left out
can be partial (only some enumerators with expl. value)
if you set enumerator values explicitly, do it for all enumerators
enum classmonth { jan = 1, feb = 2, mar = 3, apr = 4, may = 5, jun = 6, jul = 7, aug = 8, sep = 9, oct = 10, nov = 11, dec = 12 }; enum classflag { A = 2, B = 8, C = 5, D, E, F = 25 };
Conversions To/From Underlying Type
enum classmonth { jan = 1, feb = 2, mar = 3, apr = 4, may = 5, jun = 6, jul = 7, aug = 8, sep = 9, oct = 10, nov = 11, dec = 12 };
Enum → Integer
int i = static_cast<int>(month::mar); // i: 3
Integer → Enum
int i = 0; cin >> i; // make sure i ≥ 1 and ≤ 12 … month m1 = static_cast<month>(i);