Search code examples
c++staticconstantsdefinitionclass-members

Is it possible to initialize static const member object in a class in C++?


Is it possible to initialize a static constant member in a class definition? Please see below for the code,

class foo
{
  public:
    foo(int p) : m_p(p){}
    ~foo(){}

  private:
    int m_p;
};


class bar
{
   public:
     bar(){}
     ~bar(){}

   public:
     static const foo m_foo = foo( 2 ); //is this possible?
};

Many thanks.


Solution

  • Short answer:

    No, until the static member is const and is of integral or enumeration type.

    Long answer:

    $9.4.2/4 - "If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. 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."