I encountered this C++ static initialization order related query at a code review recently.
Here, I want to know if the static member variable is guaranteed to be initialized before the static object constructor is called?
MyClass.h:
typedef int (*MyFunc)(int);
class MyClass {
MyClass(MyFunc fptr) {
mFunc = fptr;
}
static MyFunc mFunc;
}
MyClass.cpp:
MyFunc MyClass::mFunc = nullptr;
MyDifferentClass.h:
MyDifferentClass {
public:
static int MyStaticFunc(int);
}
MyDifferentClass.cpp:
static MyClass myClassObj(MyDifferentClass::MyStaticFunc);
In the code, would mFunc
be initialized to nullptr
before myClassObj
gets created? The reason for the query is that if the order is not guaranteed, then mFunc
may get initialized again to nullptr
.
Global (namespace) variables or static class members 1 live for the entire execution of the program: they must be initialized before main() is run and destroyed after execution finishes.
A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present.
The reason for this is simple, static members are only declared in a class declaration, not defined. They must be explicitly defined outside the class using the scope resolution operator. If we try to access static member 'a' without an explicit definition of it, we will get a compilation error.
Initialization of Instance variables But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables. If you don't a compile time error is generated.
In the code, would
mFunc
be initialized tonullptr
beforemyClassObj
gets created? The reason for the query is that if the order is not guaranteed, thenmFunc
may get initialized again tonullptr
.
The answer to the question is "Yes".
Setting aside the issue of initialization of thread specific objects, initialization of non-local variables is carried out in the following order.
Those ( 1 and 2 above) are called static initialization.
After that, dynamic initialization is performed.
In your case, MyClass::mFunc
is initialized using constant initialization while myClassObj
is initialized using dynamic initialization. Hence, the former is guaranteed to be initialized first.
More on this topic can be found at https://timsong-cpp.github.io/cppwp/n3337/basic.start.init.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With