Home > Blogs > 30 C++ Tips in 30 Days: Tip # 26 in-class initialization of const static data members of integral types

30 C++ Tips in 30 Days: Tip # 26 in-class initialization of const static data members of integral types

By  Dec 15, 2007

Topics: Programming, C/C++

Speaking of objects with static storage, remember that you can initialize at least some types of static data members inside the class body and be rid of a separate definition of such members.

In the following class, the const static int member is declared but not initialized. The initializer appears in the definition, in a separate .cpp file:

//----first.h
class C
{
public:
   static const int i;
};

//----first.cpp
#include "first.h"
const int C::i=5; 

In standard C++ you can initialize static const members of integral types inside the class: 

//----first.h
class C
{
public:
   static const int i=5;
}; 

If you provide an in-class initializer, you shouldn't use a separate definition of this static member.

What happens if the header file is #included in several different translation units? Will the program have multiple copies of C::i? No, it won't. First, remember that this member is const, which means that the compiler can optimize it away, and use only the literal 5 instead. Secondly, linkers nowadays are clever enough to collapse multiple copies of the same entity (say a function template instantiation) into one copy so you can use this technique safely.

Notice however that you can use this initialization form only with integral type. Floating point data members, strings etc. cannot use this syntax


Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.