What is the rationale for not having static constructor in C++?

Nawaz picture Nawaz · Mar 14, 2011 · Viewed 7.4k times · Source

What is the rationale for not having static constructor in C++?

If it were allowed, we would be initializing all the static members in it, at one place in a very organized way, as:

//illegal C++
class sample
{
public:

    static int some_integer;
    static std::vector<std::string> strings;

    //illegal constructor!
    static sample()
    {
       some_integer = 100;
       strings.push_back("stack");
       strings.push_back("overflow");
    }
};

In the absense of static constructor, it's very difficult to have static vector, and populate it with values, as shown above. static constructor elegantly solves this problem. We could initialize static members in a very organized way.

So why doesn't' C++ have static constructor? After all, other languages (for example, C#) has static constructor!

Answer

lurscher picture lurscher · Mar 14, 2011

Using the static initialization order problem as an excuse to not introducing this feature to the language is and always has been a matter of status quo - it wasn't introduced because it wasn't introduced and people keep thinking that initialization order was a reason not to introduce it, even if the order problem has a simple and very straightforward solution.

Initialization order, if people would have really wanted to tackle the problem, they would have had a very simple and straightforward solution:

//called before main()

int static_main() {

ClassFoo();
ClassBar();

}

with appropriate declarations:

class ClassFoo {
 static int y;
  ClassFoo() {
   y = 1;
  }
}

class ClassBar {
  static int x;
  ClassBar() {
   x = ClassFoo::y+1;
  }
}

So the answer is, there is no reason it isn't there, at least not a technical one.