Initialization of Objects

A local automatic object or variable is initialized every time the flow of control reaches its definition. A local static object or variable is initialized the first time the flow of control reaches its definition. Consider the following example, which defines a class that logs initialization and destruction of objects, then defines three objects, I1, I2, and I3:

#include <iostream.h>

#include <string.h>

// Define a class that logs initializations and destructions.

class InitDemo

{

public:

InitDemo( const char *szWhat );

~InitDemo();

private:

char *szObjName;

};

// Constructor for class InitDemo

InitDemo::InitDemo( const char *szWhat )

{

if( szWhat != 0 && strlen( szWhat ) > 0 )

{

// Allocate storage for szObjName, then copy

// initializer szWhat into szObjName.

szObjName = new char[ strlen( szWhat ) + 1 ];

strcpy( szObjName, szWhat );

cout << "Initializing: " << szObjName << "\n";

}

else

szObjName = 0;

}

// Destructor for InitDemo

InitDemo::~InitDemo()

{

if( szObjName != 0 )

{

cout << "Destroying: " << szObjName << "\n";

delete szObjName;

}

}

// Enter main function

int main()

{

InitDemo I1( "Auto I1" );

{

cout << "In block.\n";

InitDemo I2( "Auto I2" );

static InitDemo I3( "Static I3" );

}

cout << "Exited block.\n";

return 0;

}

The preceding code demonstrates how and when the objects I1, I2, and I3 are initialized and when they are destroyed. The output from the program is:

Initializing: Auto I1

In block.

Initializing: Auto I2

Initializing: Static I3

Destroying: Auto I2

Exited block.

Destroying: Auto I1

Destroying: Static I3

There are several points to note about the program.

First, I1 and I2 are automatically destroyed when the flow of control exits the block in which they are defined.

Second, in C++, it is not necessary to declare objects or variables at the beginning of a block. Furthermore, these objects are initialized only when the flow of control reaches their definitions. (I2 and I3 are examples of such definitions.) The output shows exactly when they are initialized.

Finally, static local variables such as I3 retain their values for the entire duration of the program but are destroyed as the program terminates.