If you don't have a copy constructor, a default one will be created for you which does a shallow copy, where each member variable of one object is simply assigned to the other, as opposed to a deep copy.
Therefore if you have a pointer to a dynamically allocated buffer, then the default copy constructor is going to simply assign that pointer to the copy's pointer, rather than creating it's own new
buffer to point to and copying the contents of the buffer into the new one. eg.
class DynamicIntArray {
private:
int *_array;
size_t _size;
public:
DynamicIntArray(size_t size) : _array(new int[size]), _size(size) { }
DynamicIntArray (const DynamicIntArray &d) // copy constructor
{
delete[] _array;
_array = new int[d._size];
_size = d._size;
std::copy(_array, d._array, d._array + d._size);
}
/* destructor, assignment operator, etc */
};
If you didn't create a default copy constructor, then the default one created would simply assign d._array
to _array
, which would cause serious problems. ie. Instead of the above, it would do:
_array = d._array;
_size = d._size;
Note that if you have a copy constructor, you should probably have an assignment operator and a destructor (look up the rule-of-three).