Topic: static variable initialization order


Author: aakash <asharma.com@gmail.com>
Date: Sat, 23 Apr 2011 13:34:16 CST
Raw View
struct Base
{
   static int x;
}

int Base::x = 1;
and in file b.hpp, we have a struct
struct Derived: Base
{
   static int y;
}

int Derived::y = 2;
Is it guaranteed that when we compile these two class file, static
variable x will be initialized before static variable y?
I know that initialization of static variables are not defined, but
since x is in a base class, will it be first initialized?


--
[ comp.std.c++ is moderated.  To submit articles, try posting with your ]
[ newsreader.  If that fails, use mailto:std-cpp-submit@vandevoorde.com ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]





Author: =?ISO-8859-1?Q?Daniel_Kr=FCgler?= <daniel.kruegler@googlemail.com>
Date: Sun, 24 Apr 2011 09:53:51 CST
Raw View
Am 23.04.2011 21:34, schrieb aakash:
> struct Base
> {
>     static int x;
> }
>
> int Base::x = 1;
> and in file b.hpp, we have a struct
> struct Derived: Base
> {
>     static int y;
> }
>
> int Derived::y = 2;
> Is it guaranteed that when we compile these two class file, static
> variable x will be initialized before static variable y?
> I know that initialization of static variables are not defined, but
> since x is in a base class, will it be first initialized?

Initialization order of variables of static storage duration is
specified for many situations *if* the variables are defined in the same
translation unit. Your description does not really say whether
Base::x and Derived::y are defined in the same translation unit. Both
initializations are so-called static-initializations (more specifically:
They are constant initializations), so it depends solely on the relative
points of definitions in the same translation unit to decide on the
order. In this case I don't see how you could observe a difference,
because both initializations are independent from each other.

There does *not* exist any rule that involves base-derived relationships
for static data members, so you cannot rely on such relations, if you
have a situations where both variables are defined in different
translation units.

HTH & Greetings from Bremen,

Daniel Kr   gler


--
[ comp.std.c++ is moderated.  To submit articles, try posting with your ]
[ newsreader.  If that fails, use mailto:std-cpp-submit@vandevoorde.com ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]