Copy Constructor
Consider the following example program:
 
#include <rw/math/mathvec.h>
int main()
{
RWMathVec<double> b("[1 2 3 4]");
RWMathVec<double> d = b + 1; // (1)
}
This code illustrates the use of the copy constructor:
 
RWMathVec<T> (const RWMathVec<T>&)
The copy constructor is a very important and special constructor used by the compiler whenever a new object must be created from an old object. Why is it used in the example program? As you might intuitively expect, the result of the addition operation on the right hand side of //1 is an RWMathVec<double>. Hence, the vector d must be constructed from an object of type RWMathVec<double>, requiring the copy constructor.
Note that the presence of the addition operator + on //1 causes the compiler to invoke the global operator function with prototype:
 
template<classT>
RWMathVec<T> operator+(const RWMathVec<T>&, T);
to add b to 1. To use this operator function, the compiler must first interpret T as a double, then convert the integer 1 to a double. According to the prototype, this function returns a result of type RWMathVec<double>, which is fed into the copy constructor.
The net result is that //1 of the example program is completely equivalent to the statement:
 
RWMathVec<double> d(operator+(b, double(1)));
which is certainly a lot harder to read!
We will have more to say about how the copy constructor works once we've discussed assignment.