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?
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.
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.
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