Reputation: 63
In the following, I don't know if i'm confusing enums in C# with C++ but
I thought you could only access enumerators in enum using Forms::shape
which actually gives an error.
int main()
{
enum Forms {shape, sphere, cylinder, polygon};
Forms form1 = Forms::shape; // error
Forms form2 = shape; // ok
}
Why is shape
allowed to be accessed outside of enum without a scope operator and how can i prevent this behavior?
Upvotes: 6
Views: 174
Reputation: 10238
C++11 introduces scoped enumerations, which keep the namespace clean and also prevent unintentional combinations with int
types. Scoped enums are declared with the keyword sequence enum class
.
By using scoped enumerations, your above example then turns into this:
int main()
{
enum class Forms {shape, sphere, cylinder, polygon}; // mind the "class" here
Forms form1 = Forms::shape; // ok
Forms form2 = shape; // error
}
Upvotes: 0
Reputation: 360
In your example, the enum isn't declared inside a class so it has no particular scope. You could define a struct - a struct is a class where all members are public in C++ - that contains your enum, and use the name of that class to provide the scope.
You could also create a namespace and place your enum inside it as well. But that might be overkill.
Upvotes: 1
Reputation: 6834
I'd suggest that the underlying reason derives from C compatibility.
Upvotes: 0
Reputation: 320401
Well, because enums do not form a declarative scope. It is just the way it is in C++. You want to envelope these enum constants in a dedicated scope, make one yourself: use a wrapper class or namespace.
The upcoming C++ standard will introduce new kind of enum that does produce its own scope.
Upvotes: 5