Reputation: 2640
#include <iostream>
using namespace std;
class Sample{
public:
enum{ x = 10 };
};
int main(){
cout<<Sample::x<<endl;
return 0;
}
Why x which is enum in class is accessible using scope resolution operator in main function?
Upvotes: 1
Views: 1520
Reputation: 1018
Because enum
s in CPP has internal linkage by default i.e. they are made private if you declare them in struct or class
. So you have to use ::
(scope resolution operator) to access enumerators(enum constants).
In C, you can access enumerators directly because they are global by default.
Upvotes: 0
Reputation: 18421
Because the enum
is defined in public
area. Comment public
keyword, and you wont be able to access it. Same goes for any typedef
you declare in public/non-public area.
Upvotes: 1
Reputation: 75130
I assume you are asking why you do not have to instantiate a Sample
to access x
. The reason is that enum
s are like typedef
s: they create a new type, they don't create a variable. You can access Sample::x
the same way you could access a typedef
or a struct
/class
declaration inside the class.
Upvotes: 7