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.

Example

Consider the following example, which defines a class that logs initialization and destruction of objects and then defines three objects, I1, I2, and I3:

// initialization_of_objects.cpp
// compile with: /EHsc
#include <iostream>
#include <string.h>
using namespace std;

// Define a class that logs initializations and destructions.
class InitDemo {
public:
   InitDemo( const char *szWhat );
   ~InitDemo();

private:
   char *szObjName;
   size_t sizeofObjName;
};

// Constructor for class InitDemo
InitDemo::InitDemo( const char *szWhat ) :
   szObjName(NULL), sizeofObjName(0) {
   if( szWhat != 0 && strlen( szWhat ) > 0 ) {
      // Allocate storage for szObjName, then copy
      // initializer szWhat into szObjName, using
      // secured CRT functions.
      sizeofObjName = strlen( szWhat ) + 1;

      szObjName = new char[ sizeofObjName ];
      strcpy_s( szObjName, sizeofObjName, 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";
}
Initializing: Auto I1
In block.
Initializing: Auto I2
Initializing: Static I3
Destroying: Auto I2
Exited block.
Destroying: Auto I1
Destroying: Static I3

Comments

The preceding code demonstrates how and when the objects I1, I2, and I3 are initialized and when they are destroyed.

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 duration of the program, but are destroyed as the program terminates.

See Also

Reference

C++ Storage Classes