Overloading The Subscript Operator
Table of Contents

Introduction

When working with arrays, we typically use the subscript operator ([]) to index specific elements of an array.

Examples

** Example**

class IntList
{
private:
    int m_anList[10];
 
public:
    int& operator[] (const int nIndex);
};
 
int& IntList::operator[] (const int nIndex)
{
    return m_anList[nIndex];
}
 
int main()
{
  IntList cMyList;
  cMyList[2] = 3; // set a value
  cout << cMyList[2]; // get a value
 
  return 0;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.