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
Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With