views:

27

answers:

0

The long code below is given in Thinking in C++ by Bruce Eckel

//: C10:Initializer.h
// Static initialization technique
#ifndef INITIALIZER_H
#define INITIALIZER_H
#include <iostream>
extern int x; // Declarations, not definitions
extern int y;
class Initializer {
  static int initCount;
public:
  Initializer() {
    std::cout << "Initializer()" << std::endl;
    // Initialize first time only
    if(initCount++ == 0) {
       std::cout << "performing initialization"<< std::endl;
    x = 100;
    y = 200;
    }
  }
  ~Initializer() {
     std::cout << "~Initializer()" << std::endl;
     // Clean up last time only
     if(--initCount == 0) {
         std::cout << "performing cleanup"<< std::endl;
     // Any necessary cleanup here
     }
   }
};
// The following creates one object in each
// file where Initializer.h is included, but that
// object is only visible within that file:
static Initializer init;  

//: C10:InitializerDefs.cpp {O}
// Definitions for Initializer.h
#include "Initializer.h"
// Static initialization will force
// all these values to zero:
int x;
int y;
int Initializer::initCount;  

//: C10:Initializer.cpp {O}
// Static initialization
#include "Initializer.h"  

//: C10:Initializer2.cpp
//{L} InitializerDefs Initializer
// Static initialization
#include "Initializer.h"
using namespace std;
int main() {
   cout << "inside main()" << endl;
   cout << "leaving main()" << endl;
} ///:~   

Sorry for posting such a long code, but I can't get the whole thing that what could be the problem if additional class was not added and how it is solved by additional class?
Please clear my doubts.