Extending enums in C++?

Is there a way in C++ to extend/"inherit" enums?

I.E:

enum Enum {A,B,C};
enum EnumEx : public Enum {D,E,F};

or at least define a conversion between them?


No, there is not.

enum are really the poor thing in C++, and that's unfortunate of course.

Even the class enum introduced in C++0x does not address this extensibility issue (though they do some things for type safety at least).

The only advantage of enum is that they do not exist: they offer some type safety while not imposing any runtime overhead as they are substituted by the compiler directly.

If you want such a beast, you'll have to work yourself:

  • create a class MyEnum, that contains an int (basically)
  • create named constructors for each of the interesting values

you may now extend your class (adding named constructors) at will...

That's a workaround though, I have never found a satistifying way of dealing with an enumeration...


I've solved in this way:

typedef enum
{
    #include "NetProtocols.def"
} eNetProtocols, eNP;

Of course, if you add a new net protocol in the NetProtocols.def file, you have to recompile, but at least it's expandable.

"NetProtocols.def" will contain only the field names:

HTTP,
HTTPS,
FTP

If you were able to create a subclass of an enum it'd have to work the other way around.

The set of instances in a sub-class is a subset of the instances in the super-class. Think about the standard "Shape" example. The Shape class represents the set of all Shapes. The Circle class, its subclass, represents the subset of Shapes that are Circles.

So to be consistent, a subclass of an enum would have to contain a subset of the elements in the enum it inherits from.

(And no, C++ doesn't support this.)


A simple, but useful workaround for this c++ gap could be as follows:

#define ENUM_BASE_VALS A,B,C
enum Enum {ENUM_BASE_VALS};
enum EnumEx {ENUM_BASE_VALS, D,E,F};