TITLE: deferred initialization of globals (Newsgroups: comp.std.c++) [ This is a description of a global initialization technique found in the ARM (Annotated C++ Reference Manual). The second responder shows some source code for this. -adc ] PROBLEM: jgealow@mtl.mit.edu (Jeffrey C. Gealow) The technique described in the ARM 3.4 annotation cannot be applied to const objects since the values of the objects may not be changed. RESPONSE: James Kanze No. Const has nothing to do with the question, since objects only become const after construction. RESPONSE: jgealow@mtl.mit.edu (Jeffrey C. Gealow) I don't understand James Kanze's comment. Consider: // file nifty_library.h: // class X { public: int i; X() : i(10) {}; }; extern const X obj; class nifty_counter { static nifty_count; public: nifty_counter() { if (nifty_count++ == 0) { obj.i = 5; } } }; // file nifty_library.cc: // #include "nifty_library.h" const X obj; The intent of the statement obj.i = 5 in nifty_counter::nifty_counter() is to "initialize" obj. But formally, obj is initialized by the default constructor for class X. RESPONSE: kanze@gabi-soft.fr (J. Kanze), 27 Mar 96 But normally, you wouldn't try and do it this way, anyway. It is rare that initialization is so simple, and even rarer that it only involves public members. The usual solution would be to provide two constructors for X, a dummy which does nothing, and the real one used by the nifty_counter. Thus: [ This shows a common technique for expressing deferred initialization. Simply define an enum and a suitable constructor to represent an object which has been constructed but not yet initialized. -adc ] class X { public : enum DontInit { dontInit } ; X( DontInit ) {} X() : i( 5 ) {} private : int i ; } ; Objects to be initialized by the nifty_counter would be defined thus: X obj( X::dontInit ) ; [ Note the use of the "placement new" call below. -adc ] Nifty counter then becomes: class NiftyCounter { static int cnt ; public : NiftyCounter() { if ( cnt == 0 ) new( &obj ) X ; cnt ++ ; } } ; (Note that for NiftyCounter to work, it is absolutely essential that the definition of the object invoke a no-op constructor, since the object may in fact already be constructed.) As you can see, this works equally well for const objects.