
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Overloading array index operator [] in C++
Operator overloading has an important role in object oriented programming language features. Operator overloading is a type of compile time or static polymorphism.
Algorithm
Begin Create a class Arr and declare size of array. Inside the class, initialize all the elements by using for loop. Print the all elements. End.
Example Code
#include <iostream> #include <stdlib.h> using namespace std; const int M = 7; class Arr { private: int A[M]; int size; public: Arr(int s, int v) { if(s>M) { cout<<endl<<"This is beyond maximum size"; exit(1); } size = s; for(int i=0;i<size;i++) A[i] = v; } int& operator[](int i) { if( (i<0) || (i>=size) ) { cout<<endl<<"Error: Array out of bound"; exit(1); } return A[i]; } }; int main() { int i=0; Arr a(7,0); for(i=0;i<7;i++) a[i] = i*10; cout<<"Array elements are:"<<endl; for(i=0;i<7;i++) { int val = a[i]; cout<<val<<endl; } return 0; }
Output
Array elements are: 0 10 20 30 40 50 60
- Related Articles
- Overloading unary operator in C++?
- Rules for operator overloading in C++
- Increment ++ and Decrement -- Operator Overloading in C++
- How to implement operator overloading in C#?
- How to use Operator Overloading in C#?
- What is overloading a unary operator in C++?
- How will you explain Python Operator Overloading?
- Why is operator overloading not supported by java?
- C++ Program to Subtract Complex Number using Operator Overloading
- Operator overloading in C++ to print contents of vector, map, pair ..
- How can we do Python operator overloading with multiple operands?
- What are the basic rules and idioms for operator overloading in C++?
- Overloading in C#
- Overloading in java programming
- Overloading Operators in Python

Advertisements