Using Array objects -- What happens if you don't have a copy
constructor?
Assume the Array class is identical to the example given, except that
it doesn't have a copy constructor. It has everything else, destructor,
operator=, etc. And let's say you have a main that looks something like
Array x(20);
// set the elements of x's int array to valid int values
Array y(x); // construct y to look like x
A memory picture of x and y look as follows.
The Array object x is allocated memory for an int array and its
size is set to 20 by the default constructor.
Because we're assuming no copy constructor was written, the default
copy constructor, which does a memberwise copy, is used.
The address in arrayPtr is copied and the int in size is copied.
So that means that x and y don't have their own array. Both objects
contain pointers that point to the same int array.
Object x:
+-------------+
| __ | _________________________
|arrayPtr| -|---------->| some valid int values |
| -- | -------------------------
| __ | ^
|size |20| | /
| -- | /
+-------------+ /
/
Object y: /
+-------------+ /
| __ | /
|arrayPtr| -|----
| -- |
| __ |
|size |20| |
| -- |
+-------------+
Every time main changes a value in x's array, y's array is also getting changed.
And vice versa, when y is changed. That is very bad!
Moreover, after the program appears to end, it crashes. Do you know why?
Here's why. At the end of main, when objects x and y go out scope,
the destructor is called for them. First the destructor is called
for y and memory the int array's memory is deallocated, and then
the data member's memory are deallocated. The memory
picture for x and y now looks like:
Object x:
+-------------+
| __ |
|arrayPtr| -|----------> memory has been deallocated
| -- |
| __ |
|size |20| |
| -- |
+-------------+
Object y: memory has been deallocated
When the destructor is called for x, it crashes when trying to execute
the line of code:   delete [] arrayPtr;   because the int
array has already been deallocated.
And, no, the fix is not to comment out the delete in the destructor!
The fix is to correctly write the copy constructor.