Home > DeveloperSection > Forums > How to overload subscript operator[ ] in c ?
Pravesh Singh

Total Post:411

Points:2881
Posted on    June-14-2013 11:53 PM

 Visual C++ Visual C++ 
Ratings:


 1 Reply(s)
 1608  View(s)
Rate this:
Hi,

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

Thanks in advance. 


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    June-15-2013 4:44 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick