C++ Static Class Members

28 Apr 2013

A static class data member has static storage, meaning a program creates only ONE copy of a static class variable, regardless of the number of objects created. This property can be useful when you want to share some data among several objects of the same class.

One caveat of using static class member is that you cannot initialize it inside the class declaration, which is usually put in a header file (.h or .hpp). This is because the declaration is a description of how memory is to be allocated, but it doesn’t allocate memory.

static class member is initialzed in the file containing the class methods and the scope operator is used in the initialization to indicate to which class the static member belongs. However, one exception is that, if the static member is a const integral type or an enumeration type, it can be initialized in the class declaration itself.

A const static integral (or enumeration) can serve as a symbolic constant shared by all objects of the class in which the const static member is declared and initialzed. However, since the constant initialization is not a definition yet, you still need to define that static member in an enclosing namespace, otherwise, the linker will throw errors like ‘undefined reference to something’.

If you are defining a constant to be shared among all the instances of the class, use static const. If the constant is specific to each instance, just use const (but note that all constructors of the class must initialise this const member variable in the initialisation list).

Let’s see some example:

// Example1.h -- a static class member declared in header file
class Example1
{
    public:
        Example1();
        ~Example1();
    private:
        int len;
        static int somenumber;
}

// Example1.cpp
int Example1::somenumber = 0;

Example1::Example1()
{
    // blablablablablabla ...
}

// Example2.h -- a const static integral class member declared 
// and initialized in header file
class Example2
{
    public:
        Example2();
        ~Example2();
    private:
        int len;
        static const int somenumber = 0;
}

// Example2.cpp
const int Example2::somenumber;     // must be defined!

Example1::Example2()
{
    // blablablablablabla ...
}

REFERENCE