static
member of a class
/ struct
is a member that is not specific for a concrete instance of that class
/ struct
. Apart from some special cases, it must almost always be explicitly initialized in one of the compilation units. Then it can be accessed using the namespace, in where it was defined:
#include <iostream>
struct a {
static int z;
int i;
} l;
int a::z = 0; // initialization
int main() {
a::z = 3;
l.i = 4;
std::cout << a::z << ' ' << l.i;
return 0;
}
outputs 3 4
.
"I cant initialize the z using a initializer list."
That's because an initialization list is used to initialize members of a specific instance of that struct
by the time they are being constructed. Static member is constructed and initialized in a different manner.
"what If I had a static struct member in a class?"
The only difference is that members defined in class
are private
by default, unlike struct
, where it is public
.