next up previous
Next: myvector.h file Up: Simple Classes: myvector.h Previous: Overloading compound assignments: +=,

Improvements: More constructors

It is useful to introduce two more constructors:



class vector {
  ...
public:
  // Constructors 
  ...

  vector(const double*, int);
  vector(const vector&);
  ...
};

inline vector::vector(const double *a, int n){
  size = n;
  vec = new double[size];
  // If the allocation failed, vec is returned NULL.
  if(vec==NULL)
    {
      cerr << "FATAL vector::vector(const double *, int) can't allocate vector(" 
	   << n << ")\n";
      exit(1);
    }
  for(int i = 0; i < size; i++){
    vec[i] = a[i];
  }
}

inline vector::vector(const vector &v){
  size = v.size;
  vec = new double[size];
  // If the allocation failed, vec is returned NULL.
  if(vec==NULL)
    {
      cerr << "FATAL vector::vector(const vector &) can't allocate vector(" 
	   << v.size << ")\n";
      exit(1);
    }
  for(int i = 0; i < size; i++)vec[i] = v.vec[i];
}

The first of these converts a simple array into a vector object. We would use it as follows:

   double a[5] = {1.1., -2.2, 0.3, 44.0, 5.0};
   vector v1(a,5);
In the first statement we initialize the array a by listing values for its components, but we could have assigned values to the array by other means. The second statement constructs a vector object v1 of length 5 by copying the array values into the vector.

The second constructor, called a copy constructor, clones a vector object. Continuing from the above example, we would use it as follows:

   vector v2(v1);
This statement constructs a new vector v2 as an exact copy of the vector v1. The C++ compiler actually has a default copy constructor for any class, but we can't use it here for the same reason we can't use its default assignment operator. (See the discussion of the assignment operator above.) So it is a very good idea to supply the correct definition so someone doesn't get the default copy constructor by mistake.


next up previous
Next: myvector.h file Up: Simple Classes: myvector.h Previous: Overloading compound assignments: +=,
Carleton DeTar 2007-08-17