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 and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.