5 Cloning constructors

A constructor can contain parameters. In this section, we are interested in a parameter of the same type (that is being initialized). Extending the example that we have been using:

class Y
{
  public:
    int i;
    float f;
    char a[20];

    Y(void);
    ~Y(void);
    Y(Y original);
}

Y::Y(void)
{
  i = 0;
  f = 3.14;
  a[0] = '\0';
} 

Y::~Y(void)
{
  cout << "an object of class Y is destroyed!" << endl;
} 

Y::Y(Y original)
{
  i = original.i;
  f = original.f;
  strncpy(a, original.a, sizeof(a));
}

Let us focus on the parametrized constructor method. It requires a parameter of class Y. In this example, we simply copy all the data members directly. However, the initialization code can be anything. In other words, the initialization can choose to initialize some data members from the original, it can also contain the logic to copy a data structure that the original points to. At any rate, this constructor approach is much more flexible than the assignment operator approach.

The following example illustrates how to use this parametrized constructor:

{
  Y a;

  // initialize a
  {
    Y b(a);

    // b is cloned from a using the
    // special constructor!
  }
}


Copyright © 2006-09-05 by Tak Auyeung