Copy Constructors

Suppose we have created a Complex object with real part equal to 10 and imaginary part equal to 5:

Complex c1 = new Complex(10,5);

We now want to create a second object whose real and imaginary parts are equal to the real and imaginary parts of c1. If we do the following, we will get the wrong result:

Complex c1 = new Complex(10,2); 
Complex c2;
c2 = c1;

The problem with this is we want two separate objects whose member variables contain the same values. In the above example we just get one object.

That is, we want the following picture:

A possible correct solution is:

Complex c1 = new Complex(10,2); 
Complex c2 = new Complex(c1.getReal(),c1.getImag());

This will produce the correct result but it is quite cumbersome. Imagine if our object had 20 member variables instead of just 2.

A better solution is to write a constructor that takes an existing object and sets the member variables of the new object to the values of the existing object. The notation would look something like:

Complex c1 = new Complex(10,2); 
Complex c2 = new Complex(c1); // copies c1 values into c2

But what would the constructor look like?

public Complex(Complex c) {
   real = c.getReal();
   imag = c.getImag();
}

If you think you will be needing to copy objects, then it is a good idea to include a copy constructor.


next lecture