- 2068 Chaitra · 6 marks
Overload index operator [] for array class
Short answer
Overload operator[] with a bounds check, returning an int& reference to the array element. This allows both input (cin >> a[i]) and output (cout << a[i]). Sample elements 10 20 30 40 50 are read and displayed correctly.
Create a class having an array as member. Overload index operator ([ ]) to input and display the elements in the array.
The subscript operator [] is overloaded as a member function that takes the index and returns a reference (int&). Returning a reference lets the same function be used on both sides of an assignment: a[2] = 10; (input) and cout << a[2]; (display). A bounds check makes the class safer than a plain array.
#include <iostream>
#include <cstdlib>
using namespace std;
const int SIZE = 5;
class Array {
int arr[SIZE];
public:
int& operator[](int i) {
if (i < 0 || i >= SIZE) {
cout << "Index out of range" << endl;
exit(1);
}
return arr[i];
}
};
int main() {
Array a;
cout << "Enter " << SIZE << " elements:" << endl;
for (int i = 0; i < SIZE; i++)
cin >> a[i]; // a.operator[](i) used as lvalue
cout << "Elements are: ";
for (int i = 0; i < SIZE; i++)
cout << a[i] << " "; // a.operator[](i) used as rvalue
cout << endl;
return 0;
}
Sample run:
Enter 5 elements:
10 20 30 40 50
Elements are: 10 20 30 40 50
a[i] is translated to a.operator[](i). The subscript operator can be overloaded only as a member function.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- City class with operator overloading · Object Oriented Programming, chapter 5
- Binary operator member function one argument · Object Oriented Programming, chapter 5
- Array class template with max, min, sort · Object Oriented Programming, chapter 9
- Member function as friend of another class · Object Oriented Programming, chapter 4
- Time class: +, <= and << overloading · Object Oriented Programming, chapter 5
- Vector class addition by object argument · Object Oriented Programming, chapter 1
- Create classes from design class diagrams · Object Oriented Analysis and Design, chapter 4 · asked 2×
- Pass student array; display passed students · Computer Programming, chapter 7
- Reverse array and display via pointer · Computer Programming, chapter 9
- Accessing array elements using pointer · Computer Programming, chapter 9