ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

C++ - Overloading array subscript [], Function call () Operators - Example

Updated on June 14, 2016

1. Introduction

In this example, we will investigate how do we overload the operators [] and (). The operator [] is called indexing operator and the operator () is used for sub-scripting. When a class manages a collection of data, using these operators one can facilitate the process of retrieving the data.

The indexing operator can take a single parameter and retrieves particular element based on the index supplied. The subscript operator is usually used for getting the range of data. But this operator can be overloaded in such a way that it can take the different number of parameters. We will see the usage of these operators one by one.

The Syntax for Overloading the Indexing operator is shown below:

Overloading Index Operator
Overloading Index Operator | Source

Note that the class can maintain an internal collection and a single element is retrieved based on the index passed as a parameter. We can have different implementation for indexing. Say, for example, a class Departments is maintaining Array of a department and a user can retrieve a particular department from the Departments object using the indexing operator easily. As another example, imagine a class called Products maintains Product(Containing Product Id, Product Name) in the form of linked List. We can implement the indexing operator to take a single integer, which is actually a Product_id, and iterate through the linked list we can retrieve the product.

The syntax for the Subscript operator is shown below:

Source

The subscript operator can take different numbers of parameters. So we can provide different flavors of implementation for it. Let us start with implementing the example program.

2. IntArray class

The IntArray class support a maximum of hundred elements. Below is the code:

Source

Explanation

1. The m_Array is having the capacity of storing a hundred elements of integer data. The member variable m_length is used to know how much of data is used in the 100-element array, m_Array.

2. In the Constructor, the array is populated with incremented values ranging from 0 to supplied length. Note that we are limiting the length to a maximum of hundred. In a real implementation, the array should be constructed dynamically with the requested number of slots.

3. The PrintArray function iterates through all the element till the length and prints the value stored in the array slot.

3. Overloading: Index Operator []

Let us say you want to access 5th element of the m_Array contained 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:

Source

Note that the index supplied by the operator is used to return the array element. Also, note that the overloaded operator returns reference to the array element. This helps that operator can be used for Read as well as write operations. Now, have look at the below code that uses the overloaded indexing operator:

Source

Explanation:

1) The IntArray object is generated utilizing the maximum capacity of 100. After this PrintArray is called to print the values in the array.

2) Once all the element values are printed, the value at the location 12 is printed. Note the usage of the indexing operator, which is called on the IntArray class object b (Called Like b[12]). This statement invokes the overloaded indexing operator by passing the value of 12 to it. The indexing operator returns 12th element in the internal array m_Array. Here we use indexing operator to read element 12.

3) In these statements, array elements 10, 20, and 60 are replaced with new values. Then the array is printed. In this case, the indexing operator is used to write the data to the internal array. This is why we are returning the reference.

Output of running the above code is given below:

Source

4. Overloading: Sub-Script Operator ()

A. Sub-Script operator to perform object copy.

Now Let us implement the Sub-Script operator. The subscript operator as already told can take single multiple numbers of parameters. Have a look at the below Implementation:

Source

Explanation

1) The operator () is overloaded in such a that it does not take any parameters

2) The implementation returns the current object.

3) The return is given by value to the caller of the invoker. This means there occurs a copy on the calling side of the code.

Now have a look at the below piece calling code of code:

Source

Explanation

1) An array of 50 elements is created and then the array is printed.

2) In the first look we make think that b() is a function call. But, the Object “b” invokes the subscript operator. The calling code may confuse the person who is looking at the code. When we follow proper code convention (like ArrObj_c = ArrObj_b ()) we may avoid this kind of confusion.


B. Subscript operator that sets all array elements

Here, the operator takes a single parameter and applies the value of that parameter to the entire slots of the array. Have a look at the below code:

Source

Explanation:

1) This version of subscript operator takes single value as the argument to the function

2) The array is iterated through it length, and each element of the array is set with the value passed-in

Now look at the calling code:

Source

In the calling code, we are invoking the subscript operator with the value of 15. This 15 is passed as value to the overloaded operator. The operator sets the entire array with the value of 15.

C. Subscript operator to get a Sub-Array

In this version of overloading, we are going to get the sub-array from the main array. Have a look at the operator implementation below:

Source

Explanation

1) This version of Operator takes two parameters

2) The length is calculated based on the passed-in start and end index values.

3) Once the length is counted, a new array is created and then the values are copied to this new sub-array. This sub-array is returned to the caller.

Now look at the below code which makes use of the overloaded operator:

Source

Below is the entire code and it’s output:

#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();
}
Source

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      bob 3 years ago

      Is your constructor correct?

      if( length gtr 100) { m_lentgh = length;? } did you mean m_length = 100; ?

    • sirama profile image
      Author

      sirama 3 years ago

      Yes. But in real world development we should not place such a restriction (Allowing maximum 100 slots)

    • profile image

      kosok03 3 years ago

      You should not use void main in C++.

      It supposed to return a value and even some compilers do not support void. Signature should be int main(...).

    Click to Rate This Article