Question: How do you initialize a static member of a class with return value of some function?

Solution: Static data members are shared by all object instances of that class. Each class instance sees and has access to the same static data. The static data is not part of the class object but is made available by the compiler whenever an object of that class comes into scope. Static data members, therefore, behave as global variables for a class. One of the trickiest ramifications of using a static data member in a class is that it must be initialized, just once, outside the class definition, in the source file. This is due to the fact a header file is typically seen multiple times by the compiler. If the compiler encountered the initialization of a variable multiple times it would be very difficult to ensure that variables were properly initialized. Hence, exactly one initialization of a static is allowed in the entire program.

Consider the following class, A, with a static data member, _id:


//File: a.h
class A
{
public:
A();
int _id;
};

The initialization of a static member is done similarly to the way global variables are initialized at file scope, except that the class scope operator must be used. Typically, the definition is placed at the top of the class source file:

// File: a.cc
int A::_id;

Because no explicit initial value was specified, the compiler will implicitly initialize _id to zero. An explicit initialization can also be specified:


// File: a.cc
int A::_id = 999;


In fact, C++ even allows arbitrary expressions to be used in initializers:

// File: a.cc
int A::_id = GetId(