×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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++.

C++ program to overload subscript operator []

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

Consider the program:

#include <stdlib.h>

#include <iostream>
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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.