C++ Class Definition protective setter

Description

C++ Class Definition protective setter

#include <iostream>
using namespace std;
#include <process.h>            //for exit()
const int LIMIT = 100;          //array size
class MyArray/*from  w w  w  .  j  a  v  a  2s  .c om*/
{
   private:
       int arr[LIMIT];
   public:
       int& access(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.access(j) = j*10;     //*left* side of equal sign
   for(j=0; j<LIMIT; j++)       //display elements
   {
      int temp = sa1.access(j); //*right* side of equal sign
      cout << "Element " << j << " is " << temp << endl;
   }
   return 0;
}



PreviousNext

Related