niting112
niting112

Reputation: 2640

Why enum is accessible using scope resolution operator?

#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

Answers (3)

Premkumar chalmeti
Premkumar chalmeti

Reputation: 1018

Because enums 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

Ajay
Ajay

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

Seth Carnegie
Seth Carnegie

Reputation: 75130

I assume you are asking why you do not have to instantiate a Sample to access x. The reason is that enums are like typedefs: 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

Related Questions