What is a static constructor?

In C++, there is no static constructor. In C# (and probably in Java too), you can define static constructor which is called automatically by the runtime so as to initialize static members.

For further question and interest you can read this topic:

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


C++ doesn’t have static constructors but you can emulate them using a static instance of a nested class.

class has_static_constructor {
    friend class constructor;

    struct constructor {
        constructor() { /* do some constructing here … */ }
    };

    static constructor cons;
};

// C++ needs to define static members externally.
has_static_constructor::constructor has_static_constructor::cons;

Since we do not technically have static constructors in C++, you have to decide whether it is worth it to do something tricky to force the issue (e.g. using a static instance of a nested class), or to just slightly restructure your code to call a static initializer early in your program's life.

#include <iostream>           // cout, endl

class Foo {
   public:
      static int s_count;

      // Constructor definition
      Foo (int l, int w, int h)
      {
         cout <<"Foo ctor called." << endl;
         length = l;
         width  = w;
         height = h;

         // Increase every time object is created
         s_count++;
      }

      int vol ()
      {
         return length * width * height;
      }

      static void initCount()
      {
         s_count = 0;
      }

      static int getCount()
      {
         return s_count;
      }

   private:
      double length;     // Length of a box
      double width;      // Width  of a box
      double height;     // Height of a box
};

// Initialize static member of class Foo
int Foo::s_count;  // Initializing here is non-deterministic

int main(void) {

   Foo::initCount();  // Initializing here is deterministic

   // Print total number of objects before creating object.
   cout << "Inital Count: " << Foo::getCount() << endl;

   Foo Foo1(3, 1, 1);    // Declare box1
   Foo Foo2(8, 6, 2);    // Declare box2

   // Print total number of objects after creating object.
   cout << "Final Count: " << Foo::getCount() << endl;

   return 0;
}

Output:

$ static_init_test
Inital Count: 0
Foo ctor called.
Foo ctor called.
Final Count: 2

I like this approach better; as a silver lining, it takes the non- out of non-deterministic initialization.

There is one gotcha though -- this technique is insufficient if you are trying to initialize static const variables. For static const variables, you will have to make them private to the class and provide getters for outsiders to read them.

Note: I updated this code -- it compiles and runs successfully with no warnings via:

g++ static_init_test.cpp -std=c++11 -o static_init_test

Tags:

C++