Topic: static globals order of construction


Author: "Erez Efrati" <erez@temple.co.il>
Date: 1996/10/29
Raw View
Lets say we have the following situation:

class B {
    public:
       B (...) { name = new char [100]; name[0] = '\0';}
       void SetName (char *newName) { strcpy (name,  newName); }

    protected:
       char * name;
};

class A {
    public:
            A (...) { b.SetName("tamar" ); }     // assumes that the b is
already       // constructed.

    protected:

 static B b;
};

class C {

   public:
 C (...) {...}
   protected:

   static A a;

};

and in a CPP file:
B A::b(..);
A C::a(...);



The problem is that the order of construction of the static B and A is not
defined in the language, (or am I wrong). And being as it is, it may happen
that in the constructor of A the call to b.SetName(...) occurrs before B
got a chance to construct itself, and so the char *name will not be
initialized.

I think that the compiler can tell who needs to be initialized before who.

Erez
---
[ comp.std.c++ is moderated.  To submit articles: Try just posting with your
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu
]