YouTip LogoYouTip

Subscripting Operator Overloading

# C++ Subscript Operator [] Overloading [![Image 3: C++ Overloading Operators and Functions](#) C++ Overloading Operators and Functions](#) The subscript operator [] is typically used to access array elements. Overloading this operator enhances the functionality of operating on C++ arrays. The following example demonstrates how to overload the subscript operator []. ## Example #includeusing namespace std; const int SIZE = 10; class safearay{private: int arr; public: safearay(){register int i; for(i = 0; i= SIZE){cout<<"Index exceeds maximum value"<<endl; // Return the first element return arr; }return arr; }}; int main(){safearay A; cout<<"Value of A : "<<A<<endl; cout<<"Value of A : "<<A<<endl; cout<<"Value of A : "<<A<<endl; return 0; } When the above code is compiled and executed, it produces the following result: $ g++ -o test test.cpp $ ./test Value of A : 2 Value of A : 5 Value of A : Index exceeds maximum value0 [![Image 4: C++ Overloading Operators and Functions](#) C++ Overloading Operators and Functions](#)
← Cpp Inline FunctionsCpp Copy Constructor β†’