Lab #10, Friday, 11/30

The purpose of this lab is to give you more practice with pointers and to illustrate how to create a dynamic array with an overloaded [] operator.

One limitation of arrays is the fixed size. It would be nice if we could add or remove elements from an array. In previous programs we created a large array and only used part of it, but the unused elements waste memory. One way to avoid this problem is to make a class that creates a dynamic array of exactly the size we need.

A first version of such a class that can store integers is below. pNums is a pointer to an array of ints that is allocated to hold exactly numElements integers. The constructor sets numElements to 0 and the destructor deletes the dynamic array. The add function adds a new integer to the array. Remove should remove the last element from the array. There is also an overloaded [] operator that retrieves the integer at a specified index.

In the implementation file, most of the work is in the add function. A new array is created that is one integer larger than the current array. The current array is copied into the new one, the element to add is put at the end, and then the old array is deleted. Finally, the newly created array is stored in pNums.

The code will compile and allow you to add and access elements using []. However, the remove function is only a stub.

TO DO:

  1. Modify the [] operator so it prints an error message if the index is invalid. An invalid index is one that is negative or beyond the size of the array. Return -1 if such an error occurs. The code already prints an error message and returns -1 if nothing has been added to the array but it is accessed.
  2. Implement the remove() function so the last element in the array is removed. Use a similar process that is done in add() except shrink the size of the array by one. If there are no items in the array then nothing should happen.

Here is some sample test code you can put in main:

Show your code/program to the instructor or lab assistant for credit, or email to kjmock@alaska.edu.