< previous page page_1023 next page >

Page 1023
The class constructor DynArray (In: arrSize)
IF arrSize << 1
   Print error message
   Halt the program
Set size = arrSize
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] = 0

The class destructor ~DynArray ()
Deallocate the array pointed to by arr

In the constructor, we allocate an integer array of arrSize elements and store its base address into the pointer variable arr. Remember that in C++ any pointer can be indexed by attaching an index expression in brackets. Therefore, the assignment statement
arr[i] = 0;
does exactly what we want it to: it stores zero into element i of the array pointed to by arr.
Testing: Three things should be tested in the constructor: the two If statements and the initialization loop. To test the first If statement, we should try different values of the parameter arrSize: negative, zero, and positive. Negative and zero values should cause the program to halt. Testing the second If statement may or may not prove fruitful, depending on a particular compiler and machine. On some machines, passing a huge value of arrSize may cause the new operator to return NULL if there is not enough room on the free store. Other machines use a concept called virtual memory, which lets the machine borrow space on a disk device as if the disk were memory. In this case, the size of the free store is essentially unbounded, so the If test will always succeed. To test the initialization loop, it would suf-

 
< previous page page_1023 next page >