ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How do I overload "Array Subscript []" and "Function Call ()" Operators?

Updated on June 13, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like playing video games & reading books.

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 a class can maintain an internal collection and a single element is retrieved from it based on the index passed as a parameter to a function. One can have a variety of implementation for that. Say, for example, a class Department is holding Array of a department and a user can retrieve a particular 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 implement the indexing operator to take a single integer which is indeed a Product_id, and iterate through the Linked List. When a match found in it, we can retrieve the Product from it.

The below illustration explains the syntax for the Subscript operator:

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 utilized to identify how much of data is used in the 100-element array, m_Array.

2. In the Constructor, the array is populated 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.

3. The PrintArray function iterates through all the component 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

      kosok03 

      5 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(...).

    • sirama profile imageAUTHOR

      sirama 

      5 years ago

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

    • profile image

      bob 

      5 years ago

      Is your constructor correct?

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

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)