1. Overload Syntax For Indexing And SubScript Operators
In this example, we overload Indexing and SubScript operator to deal with an Array. When a class deals with collections, these operators help in data retrieval from it. In C++, [] is the indexing operator and () is subscript or function call operator.
The indexing operator can take a single argument and retrieves particular element from the collection based on the supplied index. Application Developers use the subscript operator for getting the range of data. But this operator can also be overloaded in such a way that it can take the different number of arguments. We will see the usage of these operators one by one.
The Syntax for Overloading the Indexing operator is shown below:

Overloading Array Index Operator – Syntax
Note that the implementing class holds a private collection. We can fetch a single item from that collection based on the index passed as an argument to the overloaded function. One can overload this operator in many ways to meet the need. Say, for example, a class Department is holding Array of a department and a user can fetch a specific department from it using the indexing operator. As another example, imagine a class called Products maintain Product(Containing Product Id, Product Name) in the form of a Linked List. We can write the indexing operator to take a single integer which is a Product_id, and iterate through the Linked List. When a match found in it, we can take the Product from it.
The below picture shows the syntax of the Subscript Operator:

Overloading Subscript Operator – Syntax
The subscript operator can take a various number of arguments. So, we can provide various flavors of implementation for it. We will write the example program for each operator.
2. The IntArray Class for SubScript and Indexing
The IntArray class supports a maximum of hundred elements. Below is the code:

IntArray Class
Explanation
- The m_Array is having the size of keeping one hundred items of integer data. The member variable m_length is to check how many slots filled in the 100-element array, m_Array.
- In the Constructor, we populate the array with increment’d values ranging from 0 to supplied length. Note that we are limiting the length to a maximum of a hundred. In a substantial implementation, the array should be built up dynamically with the desired number of slots.
-
The PrintArray function iterates through all the slots and prints the value stored in each slot.
3. Overload Indexing Operator []
Let us say you want to access the 5th piece of the m_Array which is inside the object of IntArray class. One way is adding member functions, which will set and get the data from the internal array. The other way is using the indexing operator. Have a look at the below code:

Overloading C++ Indexing Operator Example
Note that we use the index handed over by the operator to return the array item. Also, note that the overloaded operator returns reference to the array member. This helps that operator can be used for read and write actions. Now, have a look at the below code that uses the overloaded indexing operator:

Using the Overloaded Operator
Explanation
1) We set up The IntArray object with the maximum capacity of 100 items. Then we call the PrintArray function to print the values in that array.
2) Once we print all the item values, we also print the value at the location 12. Note the usage of the indexing operator, which is called on the IntArray class object b (Called Like b[12]). This statement calls the overloaded indexing operator by passing the value of 12 to it. The Index Operator returns item at 12th location. So we here perform the read action using the Index Operator.
3) In these statements, first we replace array elements 10, 20 and 60 with new values. Then we print the array. Here, we use the indexing operator to write the data to the internal array. Note, the call to the Index Operator is in the left side of the assignment. This is why our indexing operator returns the reference to the array element.
The below picture shows the result of running the above code snippet:

Program Output 1
4. Overloading SubScript Operator ‘()’
4.1 Overload SubScript Operator to Perform Object Copy
Now we will write code for the Sub-Script operator. The subscript operator can take single or multiple numbers of argument. Have a look at the below code:

Subscript Operator to Perform Object Copy
Explanation
- We overload the operator ‘()’ in such a way that it does not take any arguments.
-
The subscript operator returns the current object.
3) The return is given by value to the caller. This means there occurs a copy on the calling side of the code.
Now have a look at the below piece of calling code:

Using Overloaded Subscript Operator to Copy
Explanation
1) Here, we create an array of 50 items. Then we print the array content.
2) In a first look we may think b() is a function call. But, the Object “b” invokes the subscript operator. The calling code may confuse the person looking at it. When we follow proper code convention (like
ArrObj_c = ArrObj_b ()
) we may avoid this kind of confusion.
4.2 Overload Subscript Operator To Set All Array Items
Here, the operator takes a single argument and sets that to the entire slots of the array. Have a look at the below code:

Second Version of Overloaded Operator
Explanation
1) This version of subscript operator takes a single value as an argument to the function.
2) Here, we iterate the full array. In each pass, we set the array item with the valued passed in to the function.
The picture below shows the calling code:

Subscript Operator initializing the Array
In the calling code, we call the subscript operator with the value of 15. The operator sets the entire array with this value.
4.3. Overload Subscript Operator to Get A Sub-Array
In this version of overloading, we will get the sub-array from the main array. The below code shows how it is done:

Overloaded version to get Sub-Array
Explanation
1) This version of Operator takes two arguments.
2) The function calculates the length based on the passed-in start and end index values. We need this to create the sub-array and we will return this to the caller.
3) The function then creates a new array using the length calculated in previous step. Then the values are copied to this new sub-array. Finally, we return this sub-array to the caller.
5. Completed Example & Its Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
#include "stdafx.h" #include <iostream> using namespace std; //Sample 01: IntArray class example. Maximum array size 100 class IntArray { private: int m_Array[100]; int m_length; public: //Sample 02: Constructor IntArray(int length) { if (length > 100) m_length = length; else m_length = length; for (int i = 0; i < m_length; i++) m_Array[i] = i; } //Sample 03: Prints the elements of the array void PrintArray() { for (int i=0; i < m_length; i++) cout << m_Array[i] << ", " ; cout << endl << endl; } //Sample 04: Operator used for single value indexing int& operator[](int index) { return m_Array[index]; } //Sample 04: Operator used as getting the copy IntArray operator()() { return *this; } //Sample 05: Operator used to reset the array elements void operator()(int value) { for (int i=0; i < m_length; i++) m_Array[i] = value; } //Sample 06: Used to return the sub-array IntArray operator()(int start, int end) { int len = end - start + 1; IntArray temp(len); for (int i = 0; i < len; i++) temp[i] = m_Array[start + i]; return temp; } }; void main() { //Test 01: Create Array and Print Vales IntArray b(100); b.PrintArray(); //Test 02: Using the indexing [] set some new values cout << "The value at location 12: " << b[12] << endl; //Test 03: Set two New Values and Print the Array b[10] = 1000; b[20] = 2000; b[60] = 60000; b.PrintArray(); //Test 04: Copy the values from Array b IntArray c(50); cout << "The Array c" << endl; c.PrintArray(); cout << "The Copied Array C" << endl; c = b(); c.PrintArray(); //Test 05: Reset the Array Content to 15 b(15); b.PrintArray(); //Test 06: Get Part of the Array and Print it IntArray k = c(10,20); k.PrintArray(); } |

Output of Completed Example
- Overloaded Assignment Operator in C++
- How Do I Write A C++ VARIADIC Function using va_start, va_arg, va_end Macros?
Categories: C++
Tags: Operator Overloading, Overload []