next up previous
Next: Improvements: More constructors Up: Simple Classes: myvector.h Previous: Improvements: Vector addition

Overloading compound assignments: +=, etc.

The compound assignment ``add and assign''

   a += b;
is equivalent to
   a = a + b;
Similarly, C++ provides operators for the compound assignments -=, *=, and /=. The function names corresponding to them are operator+=, etc. For operations between pairs of vectors, the meanings of ``add and assign'' and ``subtract and assign'' are natural. We are free to overload any operator how ever we like, but to avoid confusion we take the conservative approach and define multiplication and division only with scalars. To make them work for our vectors, we need to overload them. The way this is usually done is to make them methods in the class. Then the compiler interprets a += b as
   a.operator+=(b);
Here is how we define the method:

class vector {
   ...
public:
   ...
   vector operator+=(const vector &v);
   ...
};

inline vector& vector::operator+=(const vector &v){
  if(size != v.size){
    cerr << "FATAL vector::operator+=(const vector &) size mismatch: " <<
      size << " " << " != " << v.size << "\n";
    exit(1);
  }
  for(int i = 0; i < size; i++) vec[i] += v.vec[i];
  return *this;
}

This definition is almost identical to the definition for the assignment operator above. The only difference is that we add the rhs components to the lhs, instead of copying them.

We leave it as an exercise to supply the definitions for *= and /= for the case that the rhs is a double precision number.


next up previous
Next: Improvements: More constructors Up: Simple Classes: myvector.h Previous: Improvements: Vector addition
Carleton DeTar 2007-08-17