syko syko - 1 month ago 5
C++ Question

If multiple classes have a static variable in common, are they shared (within the same scope?)

I have the following example code:

class A {
public:
static int a;
};
int A::a = 0;

class B {
public:
static A a1;
};
A B::a1;

class C {
public:
static A a1;
};
A C::a1;


int main(int argc, const char * argv[]) {
C::a1.a++;
B::a1.a++;
std::cout << B::a1.a << " " << C::a1.a << std::endl;
return 0;
}


Class B and C have class A as a static member variable.

I expected the program to print "1 1", however it prints "2 2".

If multiple classes have a static variable in common, are they shared (within the same scope?)

Answer

The staic members belong to class, it has nothing to do with objects.

Static members of a class are not associated with the objects of the class: they are independent objects with static storage duration or regular functions defined in namespace scope, only once in the program.

For your code, there's only one A::a, which is independent of B::a1 and C::a1 which are objects of class A. Both B::a1.a and C::a1.a refer to A::a.

Comments