tags:

views:

666

answers:

5

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 Base
{
   four=4, five, six

};
+4  A: 

Not possible. There is no inheritance with enums.

You can instead use classes with named const ints.

Example:

class Colors
{
public:
  static const int RED = 1;
  static const int GREEN = 2;
};

class RGB : public Colors
{
  static const int BLUE = 10;
};


class FourColors : public Colors
{
public:
  static const int ORANGE = 100;
  static const int PURPLE = 101;
};
Brian R. Bondy
+11  A: 
#include <iostream>
#include <ostream>

class Enum
{
public:
    enum
    {
        One = 1,
        Two,
        Last
    };
};

class EnumDeriv : public Enum
{
public:
    enum
    {
        Three = Enum::Last,
        Four,
        Five
    };
};

int main()
{
    std::cout << EnumDeriv::One << std::endl;
    std::cout << EnumDeriv::Four << std::endl;
    return 0;
}
Mykola Golubyev
+1: Hey, that's a cool idea.
Arnold Spence
A: 

Impossible.
But it will the same if you define enum in class, because enum doesn't have any data or functionality.
After that you can add additional enum conastants in derived classes.

bb
+1  A: 

You can't do that directly, but you could try to use solution from this article.

Kirill V. Lyadvinsky
A: 

Well, if you'll define enum with the same name in derived class and start it from last item of correspondent enum in base class, you'll receive almost what you want - inherited enum. Look at this code:

class Base
{
public:
enum ErrorType
  {
  GeneralError,
  NoMemory,
  FileNotFound,
  LastItem
  }
}

class Inherited: public Base
{
enum ErrorType
  {
  SocketError = Base::LastItem,
  NotEnoughBandwidth,
  }
}
Haspemulator