Thursday, November 17, 2011

How to overload index operator in C++?

The index operator [ ] which is normally used to access array elements can be defined for classes. The index operator is also called subscript operator or array operator. It is necessary to overload the index operator if we are making a class for array manipulation and we want to use the index operator to access the array elements in the class. However, through index operator, we can access Amy member of the class. A meaningful overloading of index operator accesses the array elements of the class rather than other members. Suppose we are making a class for safer array manipulation. First, the index operator function helps in easier access to  the array elements of the class. Secondly, the array access can also check the bound of the array for safer access. The example source code of index operator overloading is given below:
#include<iostream>
using namespace std;

class sArray{
    private:
        int arr[MAX];
    public:
        int &operator [] (int index){
            if(index < 0 || index >= MAX){
                cout<<"\n Array index out of bound\n";
                exit(1);
            }
            return arr[index];
        }
};
int main(){
    sArray sa;
    for(int i=0; i<MAX; i++){
        sa[i] = i +2;
    }
    for(int i= 0; i < MAX; i++){
        cout<<sa[i]<<"\t";
    }
    sa[MAX] = 55; //array index out of bound
    cout<<sa[MAX+1]; //array index out of bound
    return 0;
}

No comments:

Post a Comment