[comp.lang.c++] Static Constructors

phil.calvin@rose.uucp (PHIL CALVIN) (03/29/91)

  Forgive me if this is a dead issue, I have never seen mention of it
anywhere.

  Why are STATIC (for lack of a better word) Constructors not allowed??

  It seems to me that they could be useful for many types of 
classes:

//
// Windows management.
//
class Window
  {
public:
  static Window();   // Initializes window management
  Window();          // Normal object constructor
  ...
  };

  If static constructors are restricted to having zero arguments, they
could simply be implemented in the normal startup code.

//
// Alternative
//
class Window
  {
public:
  static void SetUp(); // Initializes window management
  Window();            // Constructor
  ...
  };

  In this case, the main() code (Or somewhere else) must do something
like this:

main()
  {
  Window::SetUp();     // Forget this at yer own risk
  ...
  }

  By the same argument, It would follow that STATIC destructors would
be another useful addtion to the language.

...Phil (phil.calvin@rose.uucp)
---
 

wmm@world.std.com (William M Miller) (03/31/91)

phil.calvin@rose.uucp (PHIL CALVIN) writes:
>   Why are STATIC (for lack of a better word) Constructors not allowed??
>
>   It seems to me that they could be useful for many types of
> classes:
>
> //
> // Windows management.
> //
> class Window
>   {
> public:
>   static Window();   // Initializes window management
>   Window();          // Normal object constructor
>   ...
>   };

There's really no need to change the language to accomplish this.  Jerry
Schwarz invented a technique for iostream initialization while he was at
AT&T that guarantees initialization without explicit calls in main().
Basically, it uses an auxiliary class whose constructor does the appropriate
initialization (e.g., calling Window::setup() in your alternative code).  A
static object of that class is declared in the header file, guaranteeing
that the constructor will run before any code in any file that includes the
header file.  Here's an example:

        // window.h:

        class Window {
           friend class Window_init;
           static void setup();
           static void shutdown();
        public:
           //...
           };

        class Window_init {
           static int count;    // will be defined in window.C as =0
        public:
           Window_init() {
              if (count++ == 0)         // init only once!
                 Window::setup();
              }
           ~Window_init() {
              if (--count == 0)         // terminate only once!
                 Window::shutdown();
              }
           };

        static Window_init Window_init_obj;

        // end of window.h

-- William M. Miller, Glockenspiel, Ltd.
   wmm@world.std.com