Question

struct a{static int z;}l;
(a is declared at file scope)    

I cant initialize the z using a initializer list. what does a static struct member mean?

does z(name) have external linkage and public access as well?

(I thought it meant you give it file scope and group it under a(and has public access through a object)?..why cant I initialize?)

Also....what If I had a static struct member in a class?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top