
Overloading operator [ ] ( )
In this section let us discuss special type of overloading operator i.e. [ ] and it is considered as binary operator when it involves overloading. The general form of operator [ ] is as follows:
Type class-name::operator [ ] ( int i )
{
statements;
}
since, we are dealing with array subscripting the argument should be of type ' int '. In our example we use an object 'example' and the expression
example [ 5 ]
Interpreted into this call to the operator [ ] ( ) function as :
example.operator [ ] ( 5 )
Here, the value of the expression within the subscripting operators is passed to the operator [ ] ( ) in its explicit parameter.
The example program has a constructor to initialize value of the integer array of size 10. The overloaded [ ] ( ) function returns the value of the integer array as indexed by the value of its parameter.
#include <iostream.h>
class sample
{
private:
int a[ 10 ] ;
int size ;
public:
sample ( )
{
for ( int i=0; i<10; i++ )
a [ i ] = i * 2 ;
}
int operator [ ] ( int x )
{
return a [ x ] ;
}
} ;
void main ( )
{
sample example ;
for ( int i=0; i<10; i++ )
cout << "\n location " << i << " value " << example [ i ] ;
}
Output
location 0 value 0
location 1 value 2
location 2 value 4
location 3 value 6
location 4 value 8
location 5 value 10
location 6 value 12
location 7 value 14
location 8 value 16
location 9 value 18