When using an enumeration in a class, would it be publicly accessible and why?

I use an enumeration for the class I'm working on, and I use Google to search for examples to make sure I use the enumeration correctly. I went to several sites, including the MSDN site, and the listings are listed under public rather than private. I always thought that data members are private. I'm from the base, and if so, why?

+4
source share
4 answers

These enumerations are probably used in the class interface, right? Otherwise, it would really contain them private

+3
source

An enumeration is a type, not a data member. You must make it public if users of this class need to know about it; otherwise, make it private. A typical situation where users should be aware of this is when it is used as an argument type for a public member function.

+17
source

Enumerations are not data members; they are constants / types. If you do not make them public, then other classes will not be able to 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; } 
+3
source

Common enum data is widely used in metaprogramming a template (see Boost.MPL )

 #include <iostream> template <int N> struct Factorial { enum { value = N * Factorial<N - 1>::value }; }; template <> struct Factorial<0> { enum { value = 1 }; }; int main() { auto const f10 = Factorial<10>::value; // done at compile-time std::cout << f10 << "\n"; // prints 3628800 return 0; } 

Conclusion on Ideone . The reason enum used publicly here is because the structure is just a vehicle for transferring intermediate calculations to the top-level caller, and there is no need for encapsulation. This is a crude form of evaluating a compile-time function, where the struct acts as the scope of the function and enum as the return value.

+1
source

All Articles