Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of enumerators

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?

like image 768
Kuynai Avatar asked Aug 30 '11 02:08

Kuynai


2 Answers

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.

like image 57
AnT Avatar answered Nov 12 '22 06:11

AnT


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.

like image 1
Poodlehat Avatar answered Nov 12 '22 06:11

Poodlehat