Skip to main content

Posts

Showing posts with the label overloading assignment operator

Operator Overloading -II

Let us consider some special cases of operator overloading Overloading of subscript operator:   Subscript operator ([]) can be overloaded to access the dynamically allocated array elements within an object. Using subscript operator, we can treat these like a POD array and access i th element of the array using obj[i]   class Arr { int * arr; int size; public: int & operator []( int n) ; int operator []( int n) const ; /****code *****/ }; int & Arr :: operator []( int index) { return arr[index]; } int Arr :: operator []( int index) const { return arr[index]; } int main() { Arr obj(10); for ( int i=0;i<10;i++) obj[i] = i*i; for ( int i=0;i<10;i++) cout<<arr[i]<<" "; } Output      0 1 4 9 16 25 36 49 64 81 Why do we have two functions for this operator?  Is it allowed? Is it necessary? const version of [] operator function is written so that constant object...