TITLE: enums as full class types (Private Email, 13 Mar 98) [ Response to the cpptip "extending enumerators". -adc ] TRIBBLE: David R Tribble Part of the problem is that enumerated types are not class types. They're more like the built-in types such as 'int'. Consequently, they don't have member operator functions such as operator|(). However, it's easy enough to make an enum type into a full class type, with overloaded member operators and so forth: enum E // A bitmask type { e0 = 0x01, e1 = 0x02, e2 = 0x04, e3 = 0x08, e4 = 0x10 }; class EnumE // A class encapsulation of Enum E { private: E val; // The value public: E operator =(const EnumE &o); E operator =(E e); E operator =(int i); E operator |(EnumE o); E operator |(E e); E operator |(int i); ...etc... operator E() const; // Convert to enum E operator int() const; // Convert to int }; extern void foo(E); void f() { foo(e1|e2|e3); // Always safe using enum consts EnumE v1(e1); // Defines v1 with value e1 EnumE v2 = e2; // Defines v2 with value e2 foo(v1|v2|v3); // Also works using class EnumE foo(v1|e3); // Also works mixing EnumE and E foo(e3|v2); // Also works, same thing } There are some advantages of using the class type over the enum type: 1. You can even add a default constructor for the class so that auto variables get implicitly initialized (to zero, presumably). This doesn't happen for enums and the built-in types. 2. You can add all sorts of member functions beyond the usual operators and conversions. For example, this function might be useful: const char * EnumE::image() const { switch (val) { case e0: return "e0"; case e1: return "e1"; ...etc... } } 3. You can define static member variables and functions for the class. This is useful for things like counting all the EnumE objects constructed in a program, etc. The primary drawback to using a class is that you have to go through all the trouble of defining the member operators and functions. This may take more effort than you're willing to expend to simply get an elaborated enumeration type. On the other hand, you may want stricter control over your type than what the compiler provides for a simple enum, so using a class may make sense.