|
|
|
|
|
|
|
function, to retrieve the value of an array element. We want to enhance the IntArray class so that a client of the class can create an array of any sizea size that is not bounded by a constant MAX_SIZE. Furthermore, the client should be able to specify the array size at execution time rather than at compile time. |
|
|
|
|
|
|
|
|
In this case study, we omit the Input and Output sections because we are developing only a C++ class, not a complete program. Instead, we include two sections entitled Specification of the Class and Implementation of the Class. |
|
|
|
|
|
|
|
|
Discussion: In Chapter 15's IntArray class, the private data include a fixed-size array of MAX_SIZE (which is 200) elements: |
|
|
|
|
|
|
|
|
class IntArray
{
.
.
.
private:
int arr[MAX-SIZE];
int size;
}; |
|
|
|
|
|
|
|
|
Each class object contains an array of exactly 200 elements, whether the client needs that many or not. If the client requires fewer than 200 elements, then memory is wasted. If more than 200 elements are needed, the class cannot be used. |
|
|
|
|
|
|
|
|
The disadvantage of any built-in array, such as arr in the IntArray class, is that its size must be known statically (at compile time). In this case study, we want to be able to specify the array size dynamically (at execution time). Therefore, we must design and implement a class (call it DynArray) that allocates dynamic data on the free storespecifically, an integer array of any size specified by the client code. The private part of our class will no longer include an entire array; rather, it will include a pointer to a dynamically allocated array: |
|
|
|
|
|
|
|
|
class DynArray
{
.
.
.
private:
int* arr;
int size;
}; |
|
|
|
|
|