Why does default initialization of static data member not occur? In the following example
struct data_member
{
data_member(){ cout << "data_member\n"; }
~data_member(){ cout << "~data_member\n"; }
};
struct Y
{
static data_member m;
Y(){ cout << "Y\n"; }
~Y(){ cout << "~Y\n"; }
};
Y y; //call constructor of Y
but if we delete static
specifier from data_member m
it will be default-initialized.
struct data_member
{
data_member(){ cout << "data_member\n"; }
~data_member(){ cout << "~data_member\n"; }
};
struct Y
{
data_member m;
Y(){ cout << "Y\n"; }
~Y(){ cout << "~Y\n"; }
};
Y y; //call Y() and data_member()
A static member must be defined outside the class definition. It will be initialized (can be default initialized too) at that time.
The following description from the draft standard about static
member variables should explain why it is not default initialized in the class declaration.
9.4.2 Static data members
2 The declaration of a
static
data member in its class definition is not a definition and may be of an incomplete type other than cv-qualifiedvoid
. The definition for astatic
data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of thestatic
data member shall be qualified by its class name using the :: operator.