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

Improvements: Vector addition

Here is how we make it possible to add two vectors in expressions like a + b.

class vector {
  // Binary +
  friend vector operator+(const vector &v1, const vector &v2);

inline vector operator+(const vector &v1, const vector &v2){
  if(v1.size != v2.size){
    cerr << "FATAL vector::operator+(const vector &, const vector&) size mismatch: ";
    cerr << v1.size << " " << " != " << v2.size << "\n";

  vector v(v1.size);   // Construct a temporary vector to hold the sum
  for(int i = 0; i < v1.size; i++)
    v.vec[i] = v1.vec[i] + v2.vec[i];
  return v;

Notice that this function is not a class method. It is merely a function that acts on the class and returns a new instance of the class. We make it a friend so it can access the private class members. In order to do the sum, it is necessary to create a temporary vector to hold the sum, and populate its components with the sums of the components of the vectors being added.

Carleton DeTar 2007-08-17