|
|
|
|
|
|
|
The class copy-constructor: This function is called whenever a new class object is created and initialized to be a copy of an existing class object. As with the basic class constructor, the function attempts to allocate a new dynamic array on the free store and must check the resulting pointer to see if the allocation succeeded. |
|
|
|
|
|
|
|
|
The class copy-constructor DynArray (In: array2) |
|
|
|
|
|
|
|
|
Set size = array2.size
Set arr = new int[size] // Allocate a dynamic array
IF arr is NULL
Print error message
Halt the program
FOR i going from 0 through size - 1
Set arr[i] = array2.arr[i] |
|
|
|
|
|
|
|
|
|
Testing: A copy-constructor is implicitly invoked whenever a class object is passed by value as a parameter, is returned as a function value, or is initialized by another class object in a declaration. To test the copyconstructor, you could write a function that receives a DynArray object by value, outputs the contents (to confirm that the values of the array elements are the same as in the caller's actual parameter), and modifies some of the array elements. On return from the function, the calling code should print out the contents of the original array, which should be unchanged from the time before the function call. In other words, you want to verify that when the function modified some array elements, it was working on a copy of the actual parameter, not on the actual parameter itself. |
|
|
|
|
|
|
|
|
The CopyFrom function: This function is nearly the same as the copyconstructor; it performs a deep copy of one class object to another. The important difference is that, whereas the copy-constructor creates a new class object to copy to, the CopyFrom function is applied to an existing class object. The only difference in the two algorithms, then, is that CopyFrom must begin by deallocating the dynamic array that is currently pointed to. |
|
|
|
|
|