Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!elroy.jpl.nasa.gov!decwrl!world!wmm From: wmm@world.std.com (William M Miller) Newsgroups: comp.lang.c++ Subject: Re: Static Constructors Message-ID: <1991Mar30.162905.19984@world.std.com> Date: 30 Mar 91 16:29:05 GMT References: <05c3fa6bec3a27f37740@rose.uucp> Organization: Glockenspiel, Ltd. Lines: 55 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