Thursday 17 August 2017

Start with the ARROVER3 program in Chapter 8. Keep the safearay class the same as in that program, and, using inheritance, derive the capability for the user to specify both the upper and lower bounds of the array in a constructor. This is similar to Exercise 9 in Chapter 8, except that inheritance is used to derive a new class (you can call it safehilo) instead of modifying the original class.



SOLUTION:
#include "stdafx.h"      #include "iostream"     #include "process.h"   using namespace std;
const int LIMIT = 100;
/////////////////////////////////////////////////////////////////////////////////////////
class safearay
{           protected:                    int arr[LIMIT];
            public:
                        int& operator [ ] (int n)
                        {           if( n < 0 || n >= LIMIT )           {    cout << "\nIndex out of bounds\n";       exit(1);      }
                                    return arr[n];
                        }
};
class safehilo : public safearay
{           private:            int arr[LIMIT], u_limit, l_limit;
            public:              safehilo(int l, int u) : l_limit(l), u_limit(u)          { }
                        int& operator [ ] (int n)
                        {           l_limit -= (l_limit - 0);               u_limit -= (u_limit - 100);
                                    if( n < l_limit || n >= u_limit )
                                                {           return safearay::operator[ ](n);           }
                                    return arr[n];
                        }
};
/////////////////////////////////////////////////////////////////////////////////////////
void main()
{           int low, up, j;
            cout << "Enter Lower & Upper Limits of an Array of 100 Elements Respectively: ";
            cin >> low >> up;                    safehilo sa1(low,up);
            for(j = low; j < up; j++)            sa1[j-low] = j * 10;
            for(j = low; j < up; j++)
                        {           int temp = sa1[j-low];               cout << "Element " << j << " is " << temp << endl;    }
}
OUTPUT:


0 comments: