Alex Rivera | Logout

static const Member Value vs. Member enum : Which Method is Better & Why?

Asked 2008-10-15T14:42:33.287
47

If you want to associate some constant value with a class, here are two ways to accomplish the same goal:

class Foo
{
public:
    static const size_t Life = 42;
};

class Bar
{
public:
    enum {Life = 42};
};

Syntactically and semantically they appear to be identical from the client's point of view:

size_t fooLife = Foo::Life;
size_t barLife = Bar::Life;

Is there any reason other than just pure style concerns why one would be preferable to another?

Edit
Report

1 Answer

9

One difference is that the enum defines a type that can be used as a method parameter, for example, to get better type checking. Both are treated as compile time constants by the compiler, so they should generate identical code.

answered 2008-10-15T14:50:18.527

Your Answer