Is there a pattern where I can inherit enum from another enum in C++??
Something like that:
enum eBase
{
one=1, two, three
};
enum eDerived: public eBase
{
four=4, five, six
};
Is there a pattern where I can inherit enum from another enum in C++??
Something like that:
enum eBase
{
one=1, two, three
};
enum eDerived: public eBase
{
four=4, five, six
};
Well, if you'll define
enum
with the same name in derived class and start it from last item of correspondentenum
in base class, you'll receive almost what you want - inherited enum. Look at this code:Not possible. There is no inheritance with enums.
You can instead use classes with named const ints.
Example:
As stated by
bayda
, enum's don't (and/or shouldn't) have functionality, so I've taken the following approach to your quandary by adaptingMykola Golubyev
's response:How about this? Ok an instance is created for every possible value, but besides that its very flexible. Are there any downsides?
.h:
.cpp:
Usage:
Unfortunately it is not possible in C++14. I hope we will have such a language feature in C++17. As you already got few workarounds for your problem I won't provide a solution.
I would like to point out that the wording should be "extension" not "inheritance". The extension allows for more values (as you're jumping from 3 to 6 values in your example) whereas inheritance means putting more constraints to a given base class so the set of possibilities shrinks. Therefore, potential casting would work exactly opposite from inheritance. You can cast derived class to the base class and not vice-verse with class inheritance. But when having extensions you "should" be able to cast the base class to its extension and not vice-verse. I am saying "should" because, as I said such a language feature still doesn't exist.
Impossible.
But you can define the enum anonymously in a class, then add additional enum constants in derived classes.