3

Possible Duplicate:
Is there a reason to use enum to define a single constant in C++ code?

I just came across the following snippet in some old code, with an odd use of enum:-

class MyClass
{
public:
  enum {MAX_ITEMS=16};
  int things[MAX_ITEMS];
...
} ;

This is better than #define MAX_ITEMS 16 but is it any different from static const int MAX_ITEMS=16;?

Digging back into the mists of memory, I remember some C++ compilers not allowing you to initialize consts within the class, instead requiring a separate...

const int MyClass::MAX_ITEMS = 16;

... in the .cpp source file. Is this just an old workaround for that?

Community
  • 1
  • 1
Roddy
  • 66,617
  • 42
  • 165
  • 277
  • 1
    It's possible you remember not being able to initialize something that wasn't a `static const` integral type, which was the case before C++11. – chris Jan 09 '13 at 15:33

1 Answers1

3

This is the age old "enum hack" used to initialize arrays inside the class definition.

Traditionally, pre C++03 it was not possible to initialize a static const inside the class declaration. Since array declaration needs a compile time constant index in declaration. The enum hack was used as an workaround.

class A 
{
    enum { arrsize = 2 };
    static const int c[arrsize] = { 1, 2 };

};
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • http://www.linuxtopia.org/online_books/programming_books/thinking_in_c++/Chapter08_023.html – Roddy Jan 09 '13 at 15:36
  • @Roddy: Exactly. I don't see why the Q is closed as a duplicate because it is not.It does not ask which one is better, enum or const it asks, a specific Q. – Alok Save Jan 09 '13 at 15:37