Question 4: implement class methods [8]
Suppose we are provided with the class definition shown below:
class IntArr { public: IntArr(); // Note: initially the array is NULL ~IntArr(); // deallocates the array bool Alloc(int N, int v); // allocates an array of N integers, // initializes the values to v int getSum(); // returns the sum of the array elements bool set(int v, int p); // if p is valid this stores value v in // position p and returns true // otherwise returns false bool lookup(int p, int &v); // if p is valid this sets v to the value // stored in position p and returns true // otherwise returns false private: int ArrSize; // the size of the allocated array int *Arr; // the allocated array }; |
Sample solution bool IntArr::Alloc(int N, int v) { if (Arr != NULL) { // deallocate old memory, just in case delete [] Arr; } // allocate new array and check it succeeds Arr = new int[N]; if (Arr == NULL) { ArrSize = 0; return false; } // initialize new array for (int i = 0; i < ArrSize; i++) { Arr[i] = v; } return true; } int IntArr::getSum() { if ((Arr == NULL) || (ArrSize < 1)) { return 0; } int sum = 0; for (int i = 0; i < ArrSize; i++) { sum += Arr[i]; } return sum; } |