Global objects are initialized at program startup. (For more information about construction and destruction of global objects, see Additional Startup Considerations and Additional Termination Considerations in Chapter 2.)
Local objects declared as static are initialized the first time their declarations are encountered in the program flow. The following class, introduced in Chapter 2, Basic Concepts, shows how this works:
#include <iostream.h>
#include <string.h>
// Define a class that logs initializations and destructions.
class InitDemo
{
public:
InitDemo( char *szWhat );
~InitDemo();
private:
char *szObjName;
};
// Constructor for class InitDemo.
InitDemo::InitDemo( char *szWhat )
{
if( szWhat != 0 && strlen( szWhat ) > 0 )
{
szObjName = new char[ strlen( szWhat ) + 1 ];
strcpy( szObjName, szWhat );
}
else
szObjName = 0;
clog << "Initializing: " << szObjName << "\n";
}
// Destructor for InitDemo.
InitDemo::~InitDemo()
{
if( szObjName != 0 )
{
clog << "Destroying: " << szObjName << "\n";
delete szObjName;
}
}
// Main function.
void main( int argc, char *argv[] )
{
if( argc < 2 )
{
cerr << "Supply a one-letter argument.\n";
return -1;
}
if( *argv[1] == 'a' )
{
cout << "*argv[1] was an 'a'\n";
// Declare static local object.
static InitDemo I1( "static I1" );
}
else
cout << "*argv[1] was not an 'a'\n";
}
If the command-line argument supplied to this program starts with the lowercase letter “a,” the declaration of I1
is executed, the initialization takes place, and the result is:
*argv[1] was an 'a'
Initializing: static I1
Destroying: static I1
Otherwise, the flow of control bypasses the declaration of I1
and the result is:
*argv[1] was not an 'a'
When a static local object is declared with an initializer that does not evaluate to a constant expression, the object is given the value 0 (converted to the appropriate type) at the point before execution enters the block for the first time. However, the object is not visible and no constructors are called until the actual point of declaration.
At the point of declaration, the object’s constructor (if the object is of a class type) is called as expected. (Static local objects are only initialized the first time they are seen.)