The overloading of [] is helpful to check for index out of bound. we need to return by reference in function because an expression like “arr[i]” can be used as an lvalue.
Let us see how the implementation of the operator [] in the below program
Header files of the class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include<iostream> #include<cstdlib> using namespace std; // A class to represent an integer ClsArray class ClsArray { private: int *ptr; int size; public: ClsArray(int *, int); // Overloading [] operator to access elements in ClsArray style int &operator[] (int); // Utility function to Dump contents void Dump() const; }; |
Class implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
ClsArray::ClsArray(int *p = NULL, int s = 0) { size = s; ptr = NULL; if (s != 0) { ptr = new int[s]; for (int i = 0; i < s; i++) ptr[i] = p[i]; } } int &ClsArray::operator[](int index) { if (index >= size) { cout << "ClsArray index out of bound, exiting"; exit(0); } return ptr[index]; } void ClsArray::Dump() const { for(int i = 0; i < size; i++) cout<<ptr[i]<<" "; cout<<endl; } |
Testing the array class:
1 2 3 4 5 6 7 8 9 10 |
int main() { int a[] = {1, 2, 4, 5}; ClsArray arr1(a, 4); arr1[2] = 6; arr1.print(); arr1[3] = 5; getchar (); return 0; } |
See the below sample of calling :
1 2 3 4 5 6 7 8 9 10 |
int main() { int a[] = {1, 2, 4, 5}; ClsArray arr1(a, 4); arr1[2] = 6; arr1.print(); arr1[4] = 5; getchar (); return 0; } |
The output is :
1 |
ClsArray index out of bound, exiting |
Then program called exit (0).