Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you declare enums inside or outside a class? [closed]

Should you declare enums inside or outside a class if the said enums are only used in the class member functions?

namespace nspace
{

// need to append OC, as this pollutes the current namespace
enum OUTSIDE_CLASS {OC_POINTS, OC_LINES, OC_LINE_LOOP, :::};
enum OTHER_ENUM {OE_POINTS};
class VertexBuffer
{
public:
    enum INSIDE_CLASS {POINTS, LINES, LINE_LOOP, :::};
    void foo(OUTSIDE_CLASS e);
    void bar(INSIDE_CLASS e);
}
};

// usage
nspace::VertexBuffer v;
v.foo(nspae::VB_POINTS);
v.bar(nspace::VertexBuffer::POINTS); // more pedantic
like image 728
aCuria Avatar asked Mar 09 '12 08:03

aCuria


People also ask

Where should I declare enums?

Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.

Can you declare a enum inside a class?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

Can we define enum outside a class?

Enums are used to create our own data type like classes. The enum data type (also known as Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is more powerful. Here, we can define an enum either inside the class or outside the class.

Should an enum be public or private?

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.


2 Answers

The real goal is to avoid polluting the scope (either global or namespace) and help grouping related values together (works pretty goods with autocompletion in IDE).

With C++11, you can declare strongly typed enums using:

enum class MyEnum {
  Value0,
  Value1
};

which are necessarily invoked as MyEnum::Value0 (and not Value0).

In C++03, you can more or less emulate this with:

struct MyEnum {
  enum Type {
    Value0,
    Value1
  };
};

But then the type of the enum is MyEnum::Type which is subtly different.

The lazy option is to just dump it in a class, but I still favor nesting a scoped enum, even within a class, just to make it clear that those values are not loose but instead are inter-related.

like image 89
Matthieu M. Avatar answered Oct 22 '22 12:10

Matthieu M.


If only your class members use the enum it is preferable to declare the enum inside the class.
This prevents the namespace/global space from pollution due to unneeded symbol names & also
It is more intutive for users of the class, it helps the user to know that the enum will only be used by the class.

The general rule you should follow is:
Do not add any symbol in a scope(global/namespace) which will not be accessed(& hence not needed) in that scope.

like image 31
Alok Save Avatar answered Oct 22 '22 11:10

Alok Save