Download this source file


// Class iArray is an array of ints with runtime bounds checking.
// iArray throws an "int" exception on error.
// Note how a template class would allow an array of anything, not
// just ints.
// Written 2000 by Wayne Pollock, Tampa Florida, USA.

#include <iostream>

using namespace std;

class iArray
{
 public:
   iArray ( const int n = 100 ) { size = n; rep = new int[size]; }
   iArray ( const iArray& a );
   iArray& operator= ( const iArray& a );
   ~iArray ()  { delete[] rep; }

   //Note int& and not int is returned, and "checked" exception:
   int& operator[] ( const int ) const throw ( int );

 private:
   int *rep;
   int size;
};

iArray::iArray ( const iArray& a )      // Copy Constructor.
{  size = a.size; rep = new int[size];
   for ( int i=0; i<size; ++i )
      rep[i] = a.rep[i];
}

iArray& iArray::operator= ( const iArray& a )  // Assignment operator.
{  if ( this == &a )  return *this;            // check for "a = a;"
   delete[] rep;
   size = a.size;
   rep = new int[size];
   for ( int i=0; i<size; ++i )
      rep[i] = a.rep[i];
   return *this;
}

int& iArray::operator[] ( const int index ) const throw ( int )
{  if ( index < 0 || index >= size )
      throw index;
   return rep[index];
}

int main ()
{  try
   {  iArray a(10);    // a is an iArray of 10 ints. Note unusual syntax.
      iArray b;        // b is an iArray of 100 ints.
      a[0] = 2;   b[5] = 3;
      cout << "a[0] = " << a[0] << endl;
      a[1] = b[5] * a[0];
      cout << "a[1] = " << a[1] << endl;
      a[10] = 10;      // Should cause an error!
      cout << "a[10] = " << a[10] << endl;
      a[-1] = 10;      // Should cause an error!
      cout << "a[-1] = " << a[-1] << endl;
   }
   catch ( int i )
   {  cerr << "\n\a*** Error:  Index value \"" << i
           << "\" is out of range!" << endl;
   }
   return 0;
}