Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?)

share|improve this question
    
It might be eye-opening to add objects B b1,b2 and C c1,c2, c3. – MSalters 5 hours ago
up vote 23 down vote accepted

The static 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). So both B::a1.a and C::a1.a refer to A::a.

share|improve this answer

You're not looking at multiple classes here. Both B::a1 and C::a1 are of type A. And A has a static variable a, that you accessed twice. If you also wrote A::a++, your program would have printed 3 3

To modify your example slightly:

struct A
{
    static int a;
    int b;
};
int A::a;

struct B
{
    static A a1;
};
A B::a1{0};

struct C
{
    static A a2;
};
A C::a2{0};

and the user code:

B::a1.a = 1; // A's static variable changed
B::a1.b = 2; // B's A's b changed to 2
cout << B::a1.a << ",  " << B::a1.b << endl;
cout << C::a2.a << ",  " << C::a2.b << endl;

It will print:

1, 2
1, 0

That's because all As share a, but all As have their own b. And both C and B have their own A (that they respectively share between objects of their type)

share|improve this answer

B and C both have static instances of A, these are seperate instances of A and would have different seperate instances of it's members as well. However, A::a is a static variable that is shared between all instances of A so:

&B::a1 != &C::a1 (the two a1 are seperate)

but

&B::a1.a == &C::a1.a (i.e. all A::a are the same, no matter the 'enclosing' instance of A)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.