jensa
jensa

Reputation: 2890

Enumerations within classes

Lets say I have a class C which has an attribute state which can take values down, flat or up. Rather than representing the state variable as an integer we can use enumerations instead (which ofc basically are integers). For example,

class C{
public:
    enum state {down = -1, flat = 0, up = 1};
    C(state s = flat) : st(s) {}
private:
    state st;
};

The reason for putting the enum inside the public section of the class is so that other objects can use this enumeration list as well. They would have to call

C::up

to retrieve the value up. My question is: Is the a "best practice" for either placing enum declarations inside a class defintion, or outside it (e.g. directly above it)? If the enumeration represent values/states which only has a meaning to that class then it feels intuitive to place it within the class definition.

Thank you.

Upvotes: 0

Views: 92

Answers (3)

grzkv
grzkv

Reputation: 2619

If an enum semantically only has sense in context of a class, then it is completely natural to hold it inside. If it has global meaning, it should be outside the class. In any case, the placement of the enum should reflect the semantics of the system under development.

Thus, I completely agree with your last sentences.

Upvotes: 0

TartanLlama
TartanLlama

Reputation: 65770

If you use C++11, you can use strongly typed enums. These are of the form:

enum class state
//     ^
{
    Down, Flat, Up
};

You would now access these using:

state::Down
state::Flat
state::Up

Note that this requires you to qualify/using the element, which is always good practice. However, not that these enums are type safe so cannot be arbitrarily used as integers (you probably shouldn't do this anyway).

Upvotes: 0

StelarCF
StelarCF

Reputation: 48

You most likely don't want free floating enums - they should either be in a class or namespace. If the enum only has meaning in that specific class, then it is probably best practice to place it inside - I believe SFML has an example of this with its events (sf::Event has a member of type sf::Event::EventType, which can take values such as sf::Event::KeyPressed etc.).

Upvotes: 1

Related Questions