Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using an enum in a class would it be public and why?

I am using an enum for a class I am working on and I am using Google to look for examples to make sure I am using the enum correctly. I went to several sites including the MSDN site and enums are listed under public instead of private. I always thought that data members were private. Am I off base and if so why?

like image 243
Aaron Avatar asked Aug 14 '12 16:08

Aaron


2 Answers

An enum is a type, not a data member. You should make it public if users of the class need to know about it; otherwise, make it private. A typical situation where users need to know about it is when it's used as the type of an argument to a public member function.

like image 78
Pete Becker Avatar answered Oct 01 '22 23:10

Pete Becker


Enums are not data members, they are constants/types. If you do not make them public, then other classes cannot interact with the class defining enum using enumeration names:

class A {
  public:
    void func(enumtype e) { if (e == e1) dostuff(); }
  private:
    typedef enum {e1, e2} enumtype;
};

int main() {
  A a;
  a.func(e1); // error: enumtype is private, e1 is not visible here
  return 0;
}
like image 20
perreal Avatar answered Oct 02 '22 00:10

perreal