HOW TO OVERLOAD SUBSCRIPT OPERATOR[ ] IN C ?

Pravesh Singh

Total Post:412

Points:2888
Posted by  Pravesh Singh
 1932  View(s)
Ratings:
Rate this:
Hi,

How to overload subscript operator[ ] in c++?

Thanks in advance. 
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: How to overload subscript operator[ ] in c ?

    Try this:


    syntax:

    type class-name::operator[](int index)
    {
    //operations
    }

    e.g.:
    const int SIZE=5;
    class arraytype{
    int a[SIZE];
    public:
    arraytype(){
    int i;
    for(i=0;i<SIZE;i++) a[i]=i;
    }
    int operator[ ](int i){return a[i]; }
    };
    int main( )
    {
    arraytype ob;
    int i;
    for(i=0;i<SIZE;i++)
         cout<<ob[i]<<" ";
    return 0;
      }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!