# C++ enums - which one is better?

I have a large namespace, but I don't want enum constants to be a part of it. In cases where an enum is related with a class, I coded enums inside the class so I can reach it using the class name. However, if an enum is related with namespace functions, what is the best way to do it?

1. Use another namespace and put the enum inside, so from the outside it will be the same as others with different implementations?

2. Continue and create a class with private constructors so it will be as same as others?

Classes:

class A {
public:
enum Type {
Aa,
Ab
};

Type GetType();
};

class B {
public:
enum Type {
Ba,
Bb
};

private:
B();
};

B::Type DoSomething();


Namespace:

namespace B {
enum Type {
Ba,
Bb
};
}

B::Type DoSomething();


The first case seems to abuse classes, but it can be extended later to use same coding method as the others. I am in favor of namespace, but what are your opinions?

Do not use "enum in class" for public usage. You should use namespace for the purpose. (If your compiler supports C++0x, then use enum class.)

The problem with "enum in wrapper class" is header dependency. When declaration code wants to use some "enum in wrapper class" type, then it should also references the whole class information. Because you cannot physically separate enumeration from the wrapper class (one definition rule), it'll introduces heavier header dependency.

Moreover, because in C++, there can't be two separate definitions for one class so you cannot use forward declaration technique with "enum in wrapper class" like below.

// a.h
namespace A {
enum Type {
a,
b
};
}

// b.h
namespace A {
enum Type; // forward declaration
}
A::Type function();

• Very good and solid statement. I replaced the answer with yours Jul 29 '11 at 12:09

A class is a namespace + other stuff. You aren't going to use the other stuff, so use a namespace.

I like class. Not because its better or anything, but mainly because class is a nice unit for small amounts of information that's easy to work with. namespaces less so. Some tooling often helps you work with classes better to manipulate things.

But in practice, it's not going to make a lot of difference the majority of the time.

• I can really understand what you mean, namespace feels like an overkill for the task. Jul 25 '11 at 8:36

I think you have to create a namespace e.g 'MyConst' and place into it all of your enums. Enums are in one place and easy to modify in the future.

• Problem is duplicates. It is quite easy to have them. Almost every other enum has None or similar member. Jul 29 '11 at 8:20