Thursday, 27 November 2014

Write overloading function using operator [] in C++ with examples

How to write overloading function using operator [] in C++:

The overloading of [] is useful to to check for index out of bound.
we need to return by reference in function because an expression like “arr[i]” can be used an lvalue.

Let us see how the implementation of the operator [] in the below program

Header files of the class.

#include<iostream>
#include<cstdlib> using namespace std; // A class to represent an integer ClsArray class ClsArray { private:     int *ptr;     int size; public:     ClsArray(int *, int);     // Overloading [] operator to access elements in ClsArray style     int &operator[] (int);     // Utility function to Dump contents     void Dump() const; };
Class implementation
ClsArray::ClsArray(int *p = NULL, int s = 0)
{
    size = s;
    ptr = NULL;
    if (s != 0)
    {
        ptr = new int[s];
        for (int i = 0; i < s; i++)
            ptr[i] = p[i];
    }
}
int &ClsArray::operator[](int index)
{
    if (index >= size)
    {
        cout << "ClsArray index out of bound, exiting";
        exit(0);
    }
    return ptr[index];
}

void ClsArray::Dump() const

{
    for(int i = 0; i < size; i++)
        cout<<ptr[i]<<" ";
    cout<<endl;
}

Testing the array class
int main()
{
    int a[] = {1, 2, 4, 5};
    ClsArray arr1(a, 4);
    arr1[2] = 6;
    arr1.print();
    arr1[3] = 5;
    getchar ();
    return 0;
}

See the below sample of calling
int main()
{
    int a[] = {1, 2, 4, 5};
    ClsArray arr1(a, 4);
    arr1[2] = 6;
    arr1.print();
    arr1[4] = 5;
    getchar ();
    return 0;
}

The output is
ClsArray index out of bound, exiting

Then program called exit (0).

No comments: