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 below example, assignment operator (=) is overloaded. It is used to return a reference to the element at the specified position of the MyVector class.
#include <iostream> using namespace std; class IntVector { private: int size; int *Elements; public: //class constructor IntVector(int i) { Elements = new int[i]; size = i; } //function for overloading [] int& operator[] (int index) { static int err = NULL; if(index >= 0 && index < size){ return Elements[index]; } else { cout<<"IndexOutOfBounds\n"; return err; } } }; int main (){ IntVector MyVector(10); for(int i = 0; i < 10; i++) { MyVector[i] = (i+1)*10; } for(int i = 0; i < 12; i++) { cout<<"MyVector["<<i<<"] = "<<MyVector[i]<<"\n"; } return 0; }
The output of the above code will be:
MyVector[0] = 10 MyVector[1] = 20 MyVector[2] = 30 MyVector[3] = 40 MyVector[4] = 50 MyVector[5] = 60 MyVector[6] = 70 MyVector[7] = 80 MyVector[8] = 90 MyVector[9] = 100 IndexOutOfBounds MyVector[10] = -1 IndexOutOfBounds MyVector[11] = -1
❮ C++ - Operator Overloading