I am quite confused regarding intialization and usage of C++ class/struct static members.
Let's say, that I have defined a struct MapMetaData in a header file named Constants.h. Here's how it looks -
struct MapMetaData {
static float cell_size_, origin_x_, origin_y_;
static unsigned int height_, width_;
};
Now, let's say I am using this struct in some source file.
I don't understand why can't I just directly do
MapMetaData::cell_size_ = my_value
instead of
float MapMetaData::cell_size = 0.0; // intializing the static member MapMetaData::cell_size_ = my_value? // then assigning some value to it
- Why do I need to explicily initialize the static member?
- While initializing, why do I need to specify the 'float' specifier?
- Why do I need to do the initialization globally? Why can't I just initalize it inside the scope of some function and then use it inside some another function because it is a static member after all?
Trying to call MapMetaData::cell_size_ = my_value directly without initializing, I get
undefined reference to MapMetaData::origin_x_
error.
The declaration in
Constants.htells the compiler that there will be a static variableMapMetaData::cell_size. This gives the variable a name and modules includingConstants.hcan then refer to that variable.Later, that would usually be in
Constants.cpp, the variable is defined:which tells the compiler to allocate a piece of memory in the program to store the variable. The initialization (
... = 0.0f;) tells the compiler which value to place in that piece of memory when the program starts. Static variables are always initialized. If no value is provided, i.e.:then the variable is initialized to "0" (this is not necessarily the case for non-static variables).
If the variable definition is omitted, then the storage for the variable will not be created and thus the linker cannot create the program because it cannot resolve the references to the variable. Thus an error message is given like the one you observed.
Later, you may assign a value to the variable:
this tells the compiler to create code which copies the contents of
my_valuetoMapMetaData::cell_size.Thus, these lines of code are not redundant. Each have a specific function.