Overload [] to create a generic safe array type. - C++ Class

C++ examples for Class:Operator Overload

Description

Overload [] to create a generic safe array type.

Demo Code

#include <iostream>
#include <cstdlib>
using namespace std;
// T specifies the type of the array and the non-type parameter len specifies the length of the array.
template <class T, int len> class safe_array {
   T ar[len];/*from  w ww .j a  v a  2  s  .  c  o  m*/
   int length;
   public:
   // Create a safe_array of type T with a length of len.
   safe_array();
   // Overload the subscripting operator so that it accesses
   // the elements in ar.
   T &operator[](int i);
   // Return the length of the array.
   int getlen() { return length; }
};
// Create a safe_array of type T with a length of len.
// len variable is a non-type template parameter.
template <class T, int len>  safe_array<T, len>::safe_array() {
   // Initialize the array elements to their default value.
   for(int i=0; i < len; ++i) ar[i] = T();
   length = len;
}

// Return a reference to the element at the specified index.
// Provide range checking to prevent boundary errors.
template <class T, int len> T &safe_array<T, len>::operator[](int i)
{
   if(i < 0 || i > len-1) {
      // Take appropriate action here. This is just
      // a placeholder response.
      cout << "\nIndex value of " << i << " is out-of-bounds.\n";
      exit(1);
   }
   return ar[i];
}


class myclass {
   public:
   int x;
   myclass(int i) { x = i; };
   myclass() { x = -1; }
};
int main()
{
   safe_array<int, 10> i_ar;   // integer array of size 10
   safe_array<double, 5> d_ar; // double array of size 5
   int i;
   cout << "Initial values for i_ar: ";
   for(i=0; i < i_ar.getlen(); ++i) cout << i_ar[i] << "  ";
   cout << endl;
   // Change the values in i_ar.
   for(i=0; i < i_ar.getlen(); ++i) i_ar[i] = i;
   cout << "New values for i_ar: ";
   for(i=0; i < i_ar.getlen(); ++i) cout << i_ar[i] << "  ";
   cout << "\n\n";
   cout << "Initial values for d_ar: ";
   for(i=0; i < d_ar.getlen(); ++i) cout << d_ar[i] << "  ";
   cout << endl;
   // Change the values in d_ar.
   for(i=0; i < d_ar.getlen(); ++i) d_ar[i] = (double) i/3;
   cout << "New values for d_ar: ";
   for(i=0; i < d_ar.getlen(); ++i) cout << d_ar[i] << "  ";
   cout << "\n\n";;
   // safe_array works with objects, too.
   safe_array<myclass, 3> mc_ar; // myclass array of size 3
   cout << "Initial values in mc_ar: ";
   for(i = 0; i < mc_ar.getlen(); ++i) cout << mc_ar[i].x << " ";
   cout << endl;
   // Give mc_ar some new values.
   mc_ar[0].x = 19;
   mc_ar[1].x = 99;
   mc_ar[2].x = -97;
   cout << "New values for mc_ar: ";
   for(i = 0; i < mc_ar.getlen(); ++i) cout << mc_ar[i].x << " ";
   cout << endl;
   // This creates a boundary overrun.
   i_ar[12] = 100;
   return 0;
}

Result


Related Tutorials