Search This Blog

Saturday, September 18, 2010

Overloading the [ ] subscript operator

The last operator that we will overload is the [ ] array subscript operator. In C++, the [ ] is considered a binary operator for the overloading purposes. The [ ] can be overloaded only by a member function. Therefore the general form of a member operator[ ]( ) function is as shown here
type class-name::operator[ ](int index)
{
// body ...
}
Technically, the parameter does not have to be of type int, but operator[ ]( ) function is typically used to provide array subscript and as such an integer value is generally used.
To understand how the [ ] operator works, assume that an object colled O is indexed as shown here:
O[9]
This index will translate into the following call to the operator[ ]( ) function:
O.operator[ ](9)

That is, the value of the expression within the subscript operator is passed to the operator[ ]( ) function in its explicit parameter. The this pointer will point to O, the object that generates the call.
In the following program, arraytype declares an array of five integers. Its constructor function initialises each member of the array. The overloaded operator[ ]( ) function returns the value of the element specified by its parameter.
#include
using namespace std;
const int SIZE = 5;
class arraytype {
int a[SIZE];
public:
arraytype( ) {
int i;
for (i=0;i
}
int operator[ ] (int i) { return a[i]; }
};
int main( ) {
arraytype ob;
int i;
for (i=0; i<< ob[i] << " ";
return 0;
}
This program displays the following output:
0 1 2 3 4
It is possible to design the operator[ ]( ) function in such a way that the [ ] can be used on both the left and right sides of an assignment statement. To do this return a reference to the element being indexed,
#include
using namespace std;
const int SIZE = 5;
class arraytype {
int a[SIZE];
public:

arraytype( ) {
int i;
for (i=0;i
}
int &operator[ ] (int i) { return a[i]; }
};
int main( ) {
arraytype ob;
int i;
for (i=0; i<< ob[i] << " ";
cout << "\n";
// add 10 to each element in the array
for (i=0; i
ob[i] = ob[i] + 10; // [ ] on left of =
for (i=0; i<< ob[i] << " ";
return 0;
}
This program displays:
0 1 2 3 4
10 11 12 13 14
As you can see this makes objects of arraytype act like normal arrays.

1 comment: