In the previous article Overloading [] Operator, we overloaded the [] operator in a class to access data within the class by indexing method.
The operator [] function was defined as below:
int myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}
As you can see, the above operator function is returning values, hence it could only be used on the right hand side of a statement. It’s a limitation!
You very well know that a statement like below is very common with respect to arrays:
a[1]=10;
But as I said, the way we overloaded the [] operator, statement like the one above is not possible. The good news is, it is very easy to achieve this.
For this we need to overload the [] operator like this:
int &myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}
By returning a reference to the particular element, it is possible to use the index expression on the left hand side of the statement too.
The following program illustrates this:
// Example Program illustrating
// the overloading of [] operator
// ----
// now the index expression can be
// used on the left side too
#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
// 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];
}
}
// returns a reference
int &myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}
void main()
{
myclass a(2);
cout<<a[0]<<endl;
cout<<a[1]<<endl;
// indexing expression on the
// left-hand side
a[1]=21;
cout<<a[1];
}
Related Articles: