I have the following files:
H file
class myclass
{
static int variable;
// constructor
myclass();
}
Cpp file
// initialize this variable
int myclass::variable = 0;
myclass::myclass()
{
// I use here the static variable
}
My question is: when is the static variable going to be initialized? First or after the constructor?
What if I put the
int myclass::variable = 0;
line after the class constructor definition? Will it still be initialized before a class’ object is instantiated?
A static like this will be initialised when the application starts up, which I assume will be way before you instantiate “myclass”.
Basically it doesn’t matter where you define it due to this.
However, if you create a global copy of “myclass” then I believe you can get into issues. It would be perfectly legal to put the definition before the variable initialisation e.g.
In the above case I’m pretty sure that myclass’s constructor will be called before variable is initialised. In such a case it would be best to define myclass after variable.
Edit: See http://www.parashift.com/c++-faq/static-init-order.html