-
Using enums in classes
I have been reading some tutorials and books on c++ and I noticed that the authors almost always place an enum declaration outiside a class declaration, but dont explain why.
Code:
CPerson.h
enum PersonState
{
PersonAwake = 1,
PersonHungry = 2,
PersonTired = 3,
PersonAsleep = 4
};
class CPerson
{
public:
// Person methods
private:
// Person members
};
So I guess my question is: Is it better to do it this way instead of putting the enum inside the class declaration?
-
I don't know about why they do that, but it you place it inside, then you must type the class name to access it like -> CPerson::PersonState.
If the enum is for the class only, then I usually do so. By putting it inside the class, you can also make it private - thus, none but the class can use the enum.
If you're lazy, you can always use a typedef -> typedef CPerson::PersonState PersonState;
Then you can use the enum without typing CPerson:: first.
I don't really see a reason why. Putting it inside a class also makes it stick in like a namespace - so you can use the same name for the enum over and over.
All in all, I recommend placing all such things inside the classes.
-
Thanks
I have always placed enums inside classes anyway. I just wondered if there was a certian reason for it.
-
Just another thought.
If you make the enum without a name ( which is probably pointless then the enum values will be accessed just like a public variable.
Code:
class CSomething
{
private:
//
public:
enum
{
A = 0,
B,
C
};
};
//Then access the enum
if ( SomeInt == CSomething::A )
return 0;
//Or something like that, or however your going to use it
Hope that helps alittle at least.
-
Again, which kinda defines the purpose of an enum. Enums are mostly used to define a set of values a specific parameter can hold. And if the enum has no name... well, then you can't define such a specific variable.
-
IMHO, enums should always be contained by a class or namespace. Otherwise, you will have name conflicts just like you get between other types of identifiers. In other words, instead of:
Code:
enum CarModel
{
Toyota,
BMW,
Ford
};
class Car
{
public:
Car(CarModel model_p) : model(model_p) { }
private:
CarModel model;
};
You should instead place the enumeration inside the class:
Code:
class Car
{
public:
enum Model { Toyota, BMW, Ford };
Car(Model model_p) : model(model_p) { }
private:
Model model;
};
This way, external code will refer to Car::Toyota instead of just Toyota. If the enumeration is conceptually a part of a class, or used to describe objects of a class, then it should be contained in the class.
A "bare" enumeration which is not closely related to any single class should at least go into a namespace, not the global namespace. For instance declaring an enum with values Yes, No, Maybe is highly likely to conflict with some other enumeration.