In this post, we will write a C++ program to overload [] binary operator.

C++ program to overload [] binary operator


C++ program Binar operator [ ] overloading

#include<iostream>
#include<conio.h>
#include<process.h>

using namespace std;

const int limt = 10;

class array
{
    private:
        int arr[limt];

    public:
        int& operator [](int n)
        {
            if(n<0 || n >= limt)
            {
                std::cout<<"Index out of bound";
                getch();
                exit(1);
            }
            return arr[n];
        }
};

int main()
{
    system("cls");

    array sal;

    for(int j=0;j<limt;j++)
        sal[j] = j*10;
    for(int j=0; j<limt;j++)
    {
        int temp = sal[j];
        std::cout<<"Elements "<<j<<"s"<<temp<<std::endl;
    }

    getch();
    return 0;
}



Output

Elements 0 is 0
Elements 1 is 10
Elements 2 is 20
Elements 3 is 30
Elements 4 is 40
Elements 5 is 50
Elements 6 is 60
Elements 7 is 70
Elements 8 is 80
Elements 9 is 90