
                                    EXPLODE
                                       
Light construction

   
   
   by Richard Treon of QA Training
   
   Constructors (CTORs) and destructors (DTORs) are fundamental to the
   rules of integrity and robustness in the C++ implementation of
   objects. For a start, they guarantee the proper construction of an
   object and a thorough clean-up after an object has had a useful life.
   
   A constructor is a routine which takes the raw memory allocated for an
   object and fills in useful initial values for each of the data members
   which constitute the object's state. Simple, built-in data members
   will get filled with 'zero' or other feasible values; pointers and
   references will receive appropriate addresses, which could be a safe
   '0', and, finally, component objects are supplied with enough
   information to construct themselves. The last process describes that
   lovely recursive mechanism, ie each object is responsible for its own
   new built-in's: the others 'look after themselves'.
   
   Composition is one of C++'s reusability tools. The construction of a
   component is a miraculous event. Consider the following code example :
class Money
{
public:
  Money(double v = 0.0, const char * cn = "Stirling", int r = 100);
  ...
private:
  String currencyname;
  int major;
  int minor;
  int ratio;
  ...
};

   
   
   The constructor takes a double and an int argument that sorts out the
   numerical value etc. The const char * argument is required to
   construct the String component. The constructor's definition is:
class Account
{
public:
  Account (const char * n = "", double bal = 0.0);
  ...
private:
  String name;
  Money balance;
  String credit_type;
  ...
};

   
   
   The constructor definition looks like this :
Account::Account(const char * n, double bal)
                : name(n), balance(bal, "US Dollars"){};

   
   
   The Account class has used all three of the facilities which reduce
   the complexity of its constructor. First, it takes advantage of the
   default argument in the Money constructor to construct the Money
   component with a default ratio, ie 100. Second, the Account designer
   has used a constant literal in the constructor, ie "US Dollars". Last,
   the credit_type component is constructed using the String default
   constructor and is not even mentioned in the initialisation list. All
   three mechanisms reduce the number of items required by the client to
   construct an Account object.
   
   If you want to offer your classes as successful components, it is a
   good idea to provide both default constructors and default arguments.
   This will offer the opportunity for 'deep' composition, without the
   need to have long argument lists in the constructors of the composite
   classes.
