Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending enums in C++?

Tags:

c++

enums

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?

like image 697
cvb Avatar asked Nov 26 '09 17:11

cvb


People also ask

Can we extend enum in C?

Answers. Yes, you can easily define a enumeration extending existing enum.

Can you extend enums?

No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.

Can enum extend another enum in C#?

This is not possible. Enums cannot inherit from other enums.

Can an enum be extended in C++?

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).


1 Answers

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...

like image 117
Matthieu M. Avatar answered Oct 05 '22 13:10

Matthieu M.