OOPortal
J2EEOnline RationalDB
prev prev
Course navigation
Overloading the subscript operator
A safe array

Here is the implementation of a safe array that was used in Building Classes in C++:
//Implementation of a safe array type vect
class vect {
public:
   explicit vect(int n = 10);
   ~vect() { delete []p; }
   int& element(int i);        //access p[i]
   int  ub() const
     { return (size - 1); }  //upper bound
private:
   int*  p;
   int   size;
};

vect::vect(int n) : size(n)
{
   assert(n > 0);
   p = new int[size];
   assert(p);
}

int& vect::element(int i)
{
   assert (i >= 0 && i < size);
   return p[i];
}
Course navigation