Creates safe array, index values are checked before access, uses overloaded [] operator for both put and get - C++ Class

C++ examples for Class:Operator Overload

Description

Creates safe array, index values are checked before access, uses overloaded [] operator for both put and get

Demo Code

#include <iostream>
using namespace std;
#include <process.h>           //for exit()
const int LIMIT = 100;         //array size
class MyArray//from  w  ww . ja  v  a2  s  .  com
{
   private:
   int arr[LIMIT];
   public:
   int& operator [](int n)  //note: return by reference
   {
      if( n< 0 || n>=LIMIT )
         { cout << "\nIndex out of bounds"; exit(1); }
      return arr[n];
   }
};
int main()
{
   MyArray sa1;
   for(int j=0; j<LIMIT; j++)  //insert elements
      sa1[j] = j*10;           //*left* side of equal sign
   for(int j=0; j<LIMIT; j++)      //display elements
   {
      int temp = sa1[j];       //*right* side of equal sign
      cout << "Element " << j << " is " << temp << endl;
   }
   return 0;
}

Result


Related Tutorials