C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

Overload subscript operator [] in C++

Learn: How to overload subscript operator ([]) in C/C++ programming language? In this article, we are implementing method using subscript operator ([]) overloading.

Read: Operator overloading and its rules in C++.

In this program, we are going to overload subscript operator ([ ]) overloading.

Consider the program:

#include <iostream>
#include <stdlib.h>
using namespace std;

const int MAX=5;

class MyArray
{
	//private Data Members
	private: 
	int Arr[MAX];
	int size;  // size alway less then or equal to MAX
	
	public:
	//perameterized constructor
	MyArray(int s, int v)
	{
		if(s>MAX)
		{
			cout<<endl<<"This is beyond maximum size";
			exit(1);
		}                
		size = s;

		//Initialize all array elements
		for(int i=0;i<size;i++)
			Arr[i] = v;
	}

	int& operator[](int i)
	{
		if( (i<0) || (i>=size) )
		{
			cout<<endl<<"Error: Array out of bound";
			exit(1);
		}
		return Arr[i];
	}
};

int main()
{
	int i=0;

	//size of array is 3
	MyArray arr(3,0); 

	//assign value to array elements
	for(i=0;i<3;i++) 
		arr[i] = i*20;

	cout<<"Array elements are:"<<endl;
	//Print value of array elements
	for(i=0;i<3;i++) 
	{
		int VAL = arr[i];  
		cout<<VAL<<endl;
	}
	
	return 0;
}

Output

Array elements are:
0
20
40 








COMMENTS