georgiana_e
georgiana_e

Reputation: 1869

C++ standard for defining public variable static const integer

Where should I define a static const integer member variable in c++, in the header file where the class it is defined or in a cpp file?

It complies in both situation, If I let the definition inside the header file and If I move the definition in a cpp file, but which is the c++ standard?

Upvotes: 0

Views: 816

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

Here is a full quote from the C++ Standard about constant static members:

If a non-volatile const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignmentexpression is a constant expression (5.19). A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer.

So if a const static member is not ODR-used then its definition outside the class is not required.

Note: by the way in this context it is unimportant whether a const static member is public or not.

Upvotes: 1

Hamza
Hamza

Reputation: 1583

You have to define your static member outside the class definition and provide the initailizer there.

For Standard method first do something like this

Declare static variable in header file

class Something
{
public:
    static const int s_nValue;
};

On top of cpp file initialize it like

const int Something::s_nValue = 1;

Upvotes: 0

Related Questions