views:

119

answers:

1

Hello, I don't know if it is possible to do this, but I have tried several ways and nothing seems to work. Basically I need to access the same static member from several files which include the same class definition.

// Filename: S.h

class S {
public:
    static int foo;

    static void change(int new_foo) {
        foo = new_foo;
    }

};

int S::foo = 0;

Then in a class definition (other .cpp file) I have:

// Filename: A.h

#include "S.h"    

class A {
public:
    void do_something() {
        S::change(1);
    }
};

And in another file:

// Filename: program.cpp

#include "S.h"
#include "A.h"

int main (int argc, char * const argv[]) {
    A a = new A();
    S::change(2);        

    std::cout << S::foo << std::endl;

    a->do_something();

    std::cout << S::foo << std::endl;

}

Now, I would expect the second function call to change the S::foo to 1, but the output is still:

2

Is the A.h file creating a local copy of the static class?

Thank you Tommaso

+11  A: 

This line:

int S::foo = 0;

needs to be in exactly one source file, not in the header. So move it from S.h to S.cpp.

interjay
+1 damn, you were faster :-)
Péter Török
Which is to say it should not be in the header.
Jukka Dahlbom
Great, thank you. I was just reading http://www.acm.org/crossroads/xrds2-4/ovp.html and found the same solution, but thanks anyway, you deserve the accepted answer :)
tunnuz
Are there any drawbacks in putting the methods code in the header?
tunnuz
If more than one source file includes that header (which is often the case) the variable will be defined twice, which depending on context can lead to anything from a compiler error to massively confusing bugs.
Toji
Some drawbacks for putting method code in headers: 1. Possibly longer compilation times. 2. Any needed `#includes` would need to be put in the header as well.
interjay
@tunnuz, also use guards to avoid multiple inclusion, your main program includes "s.h" twice.
Neeraj
Advantage to putting method in header: templates require it that way. Compilation time won't really be affected one way or the other. One convention is to turn `static` data members into static locals of static members in the header file. This also prevents issues with order of initialization.
Potatoswatter