C++ - Subscript Operator Overloading
Subscript operator [ ], like the function-call operator, is considered a binary operator. The declaration is identical to any binary operator, with the following exception:
- It can not be declared as a non-member function. It must be a non-static member function.
- It should take a single argument. The argument can be of any type and designates the desired array subscript.
Example: overloading subscript operator
In the example below, assignment operator (=) is overloaded. It is used to return a reference to the element at the specified position of the vector class.
#include <iostream> using namespace std; class vector { private: int size; int *Elements; public: //class constructor vector(int i) { Elements = new int[i]; size = i; } //function for overloading [] int& operator[] (int index) { if(index >= 0 && index < size){ return Elements[index]; } else { cout<<"IndexOutOfBounds\n"; exit(0); } } }; int main (){ vector myVec(10); for(int i = 0; i < 10; i++) { myVec[i] = (i+1)*10; } for(int i = 0; i < 12; i++) { cout<<"myVec["<<i<<"] = "<<myVec[i]<<"\n"; } return 0; }
The output of the above code will be:
myVec[0] = 10 myVec[1] = 20 myVec[2] = 30 myVec[3] = 40 myVec[4] = 50 myVec[5] = 60 myVec[6] = 70 myVec[7] = 80 myVec[8] = 90 myVec[9] = 100 myVec[10] = IndexOutOfBounds
❮ C++ - Operator Overloading