0

Does constant static member variables of a class or a struct in C++ need not be defined separately?

Is this correct?

struct test
{
    const static int x;
};

int test::x;
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
RK-
  • 12,099
  • 23
  • 89
  • 155
  • possible duplicate of [Initializing private static members](http://stackoverflow.com/questions/185844/initializing-private-static-members) – Martin York Aug 24 '11 at 06:27
  • @Martin: Not quite a duplicate as `x` isn't private here. (Although this doesn't matter in the linked question, the questioner in that question originally though it did.) – CB Bailey Aug 24 '11 at 06:31
  • @Charles Bailey: The answer to the question is the same. There is no point in providing the same answers when it already exists. – Martin York Aug 24 '11 at 06:41

1 Answers1

5

No that's not correct. The definition must match the declaration and x is const int, not int. As a const variable of POD type it also needs to be initialized. E.g.

const int test::x = 0;

As a const static member of integral type, it is also allowed to supply the initializer in the definition of the class instead.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • I was going to answer, but there's no point. Everything is said above! – Shlublu Aug 24 '11 at 06:29
  • Charles: Thanks. If I can initialize a const static variable in class itself, then why this probelm http://stackoverflow.com/questions/1563897/c-static-constant-string-class-member – RK- Aug 24 '11 at 06:33
  • 2
    @Krishnan: You are only allowed to initialize data members in the class body if they are `static` members of `const` integral or `const` enumeration types. `std::string` does not meet these requirements. The accepted answer of the question that you link to says exactly this. – CB Bailey Aug 24 '11 at 06:38
  • 1
    Note that even if you initialize a `static const` integral type in the declaration, technically you must still provide a single definition somewhere if it's used in the program. 9.4.2/4 says, "The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer." However, most (all?) compilers don't seem to care. – Michael Burr Aug 24 '11 at 08:03