Seeking clarity regards C++ static member initialization

75 views Asked by At

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.

1

There are 1 answers

2
nielsen On

The declaration in Constants.h tells the compiler that there will be a static variable MapMetaData::cell_size. This gives the variable a name and modules including Constants.h can then refer to that variable.

Later, that would usually be in Constants.cpp, the variable is defined:

float MapMetaData::cell_size = 0.0f;  // Explicit initialization

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.:

float MapMetaData::cell_size;  // Implicit initialization

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:

MapMetaData::cell_size = my_value;

this tells the compiler to create code which copies the contents of my_value to MapMetaData::cell_size.

Thus, these lines of code are not redundant. Each have a specific function.