Declaration of Static Objects

An object can be declared with static storage class using the static or extern keyword. Local objects must be explicitly declared as static or extern to have static storage class. Global objects (objects declared outside all functions) that are declared with no storage-class specifier are assumed to be extern.

Initialization

Global objects of static storage class 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, on topic and topic, respectively.)

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, 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.

int 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";

return 0;

}

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.)

Destruction

Local static objects are destroyed during processing of the termination functions specified by atexit.

If a static object was not constructed because the program's flow of control bypassed its declaration, no attempt is made to destroy that object.