Overloading [] Operator

Have a look at the following code fragment:


  myclass a(3);

cout<<a[0];

Doesn’t it look awkward!


Yes it does, because we have overloaded he [] operator and given it some special
meaning.


In C++, it is possible to overload the [] operator
and give it a different meaning
rather then the usual object indexing.


The general form for overloading [] operator is:


  ret-type operator[](int);

It is considered a binary operator hence when declared as a member, it accepts
one explicit argument (usually int).


Although you are free to accept any type of argument but sticking to the original
concept of indexing, it would always be an integer.


ob[i];


When the compiler encounters the above expression (with the [] operator overloaded)
the [] operator
function
is called as below:


ob.operator[] (1)


The argument ‘1’ is passed explicitly while ‘ob’ is
passed implicitly using the ‘this’
pointer.


Enough discussion, now lets get on to some action!


Below is the example program illustrating the overloading of [] operator:



// Example Program illustrating
// the overloading of [] operator
#include <iostream.h>

class myclass
{
// stores the number of element
int num;
// stores the elements
int a[10];

public:
myclass(int num);

int operator[](int);
};

// takes the number of element
// wished to be entered.(<=10)
myclass::myclass(int n)
{
num=n;
for(int i=0;i<num;i++)
{
cout<<"Enter value for element "<<i+1<<":";
cin>>a[i];
}
}

int myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];

// else
return NULL;
}

void main()
{
myclass a(3);

cout<<a[0]<<endl;
cout<<a[2]<<endl;

// out of bound
cout<<a[3]<<endl;
}


Related Articles:


Check out this stream