Static members initialization order

1
2
3
4
5
6
7
8
struct Foo
{
	static int s1;
	static int s2;
};

int Foo::s1 = 6;
int Foo::s2 = s1 * 2;


Is s1 guaranteed to be initialized first so i can init s2 safely?
Of course, the compiler reads from top to bottom, so it will assign s1 to 6 then calculate s2
closed account (zb0S216C)
In addition to Tony's post: The order of destruction is the opposite of construction, which means Foo::s2 is destroyed first, followed by Foo::s1.

Wazzak
Ok, thanks. One more stupid question, if i put it like this:
1
2
3
4
5
6
//Foo.hpp
struct Foo
{
    static int s1;
    static int s2;
};


1
2
3
//Foo.cpp
int Foo::s1 = 6;
int Foo::s2 = s1 * 2;


and use this elsewhere:
1
2
3
4
5
6
7
//Bar.cpp
#include "Foo.hpp"

int func()
{
    return Foo::s2 * 3;
}


Is it guaranteed for s1 & s2 to be initialized before used like this?
Is there some situation when bad thing can happen?

How do i know in witch order cpp files are "translated"?
static variables are initialized in the order they are defined.
The order of initialization between different files is not specified.
Last edited on
So it means behavior is undefined, it might work or not?
I can't use this safely then?

The code you posted is safe because both of them is defined in the same file (Assuming func() is not called before main).

If you put int Foo::s2 = s1 * 2; inside Bar.cpp then it is not safe because you can't know if s1 has been initialized before s2.
Last edited on
So the rule is to put all static members init in one cpp file?

Thanks.
Last edited on
All static members of the same class, yes. You normally don't spread the definition of class members all over the place anyway so it shouldn't be hard to follow.

Exception is if you have another class Bar with a static member s3 that needs s1 or s2 to be initialized. Then you have to define s3 in the same file as s1 and s2 but I find that bad design. You shouldn't really have to do that.
Last edited on
Thanks for your help.
I forgat to ask about this one too:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Foo.hpp
struct Foo
{
    static int s1;
    static int s2;

    static int func()
    {
         return s2 * 3;
    }
};
...
// Foo.cpp
int Foo::s1 = 6;
int Foo::s2 = s1 * 2;


Is s2 guaranteed to be initialized first so i can call Foo::func() safely?
Same thing if i put declaration of func() in cpp?
Last edited on
Functions are not initialized so only thing that can go wrong is if func() is called before s2 has been initialized which can only happen if func() is called before main() is called. This is true for any kind of function.
Thanks.
Topic archived. No new replies allowed.