Wednesday, August 29, 2007

Overloading [] Operator

Have a look at the following code fragment:

  myclass a(3);


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.


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];

    myclass(int num);

    int operator[](int);

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

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

    // else
    return NULL;

  void main()
    myclass a(3);


    // out of bound

Related Articles:

No comments:

Post a Comment

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.