Overloading Subscript or array index operator [] in C++
Last Updated :
02 Jul, 2024
The Subscript or Array Index Operator is denoted by '[]'. This operator is generally used with arrays to retrieve and manipulate the array elements. This is a binary or n-ary operator and is represented in two parts:
- Postfix/Primary Expression
- Expression
The postfix expression, also known as the primary expression, is a pointer value such as array or identifiers and the second expression is an integral value. In the second expression we can also include the enumerated values.
Syntax:
postfix-expression[expression];
Example: Ramswarup[10];
Here the Ramswarup is an array and the above
statement print the value which is held by
Ramswarup at index position 10.
The primary-expression followed by the subscript operator is the pointer and it can be an integral value but the one must keep in mind that one of expression among two expressions must be a pointer value and it does not matter whether the second one is of an integral order or not.
Example:
CPP
// CPP program to demonstrate []
// operator
#include <iostream>
using namespace std;
int main()
{
char name[] = "Ramswarup Tushar Nilesh Subhash";
// Both of the statement prints same thing
cout << name[5] << endl;
cout << 5 [name] << endl;
return 0;
}
Explanation:
In the above example both "cout" statement provides similar output due to the exclusive property of the subscript operator. The compiler reads both the statement in a similar way, so there is no difference between the *(name + 5) and the *(5 + name).
Positive and Negative Subscripts
The first element of an array is stored at index 0. The range of a C++ array is from array[0] to array[size - 1]. However, C++ supports positive and negative subscripts. Negative subscripts must fall within array boundaries; if they do not, the results are unpredictable. The following code shows positive and negative array subscripts:
CPP
// CPP program illustrating the
// positive and negative subscripts
#include <iostream>
using namespace std;
// Driver Method
int main()
{
int intArray[1024];
for (int i = 0, j = 0; i < 1024; i++) {
intArray[i] = j++;
}
// 512
cout << intArray[512] << endl;
// 257
cout << 257 [intArray] << endl;
// pointer to the middle of the array
int* midArray = &intArray[512];
// 256
cout << midArray[-256] << endl;
// unpredictable, may crash
cout << intArray[-256] << endl;
}
Output512
257
256
60426920
The negative subscript in the last line can produce a run-time error because it points to an address -256 positions which can be lower in memory than the origin of the array. The pointer midArray is initialized to the middle of intArray; it is therefore possible (but not recommended) to use both positive and negative array indices simultaneously. Array subscript errors do not generate compile-time errors, but they might yield unpredictable results. We have introduced Operator Overloading. In this post overloading of index operator [] is discussed. Following are some useful facts about overloading of [].
- Overloading of [] may be useful when we want to check for index out of bound.
- We must return by reference in function because an expression like "arr[i]" can be used an lvalue.
Following is C++ program to demonstrate overloading of array index operator [].
CPP
// Overloading operators for Array class
#include <cstdlib>
#include <iostream>
using namespace std;
// A class to represent an integer array
class Array {
private:
int* ptr;
int size;
public:
Array(int*, int);
// Overloading [] operator to access elements in array
// style
int& operator[](int);
// Utility function to print contents
void print() const;
};
// Implementation of [] operator. This function must return
// a reference as array element can be put on left side
int& Array::operator[](int index)
{
if (index >= size) {
cout << "Array index out of bound, exiting";
exit(0);
}
return ptr[index];
}
// constructor for array class
Array::Array(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];
}
}
void Array::print() const
{
for (int i = 0; i < size; i++)
cout << ptr[i] << " ";
cout << endl;
}
// Driver program to test above methods
int main()
{
int a[] = { 1, 2, 4, 5 };
Array arr1(a, 4);
arr1[2] = 6;
arr1.print();
arr1[8] = 6;
return 0;
}
Output1 2 6 5
Array index out of bound, exiting
Const-Correctness
Overloading both const and non-const versions of the subscript operator ([]) ensures that elements can be accessed in a read-only manner when the object is const, preventing unintended modifications to const data types.
Implementing both versions of the subscript operator is a best practice in C++ to maintain clarity and adhere to const-correctness principles, enhancing code safety and predictability.
Example:
C++
#include <cstdlib>
#include <iostream>
using namespace std;
// A class to represent an integer array
class Array {
private:
int* ptr;
int size;
public:
Array(int*, int);
// Overloading [] operator to access elements in array
// style
int& operator[](int);
const int& operator[](int) const;
// Utility function to print contents
void print() const;
};
// Implementation of non-const [] operator. This function
// must return a reference as array element can be put on
// the left side
int& Array::operator[](int index)
{
if (index >= size) {
cout << "Array index out of bound, exiting";
exit(0);
}
return ptr[index];
}
// Implementation of const [] operator. This function allows
// read-only access
const int& Array::operator[](int index) const
{
if (index >= size) {
cout << "Array index out of bound, exiting";
exit(0);
}
return ptr[index];
}
// Constructor for array class
Array::Array(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];
}
}
// Utility function to print contents
void Array::print() const
{
for (int i = 0; i < size; i++)
cout << ptr[i] << " ";
cout << endl;
}
// Driver program to test above methods
int main()
{
int a[] = { 1, 2, 4, 5 };
Array arr1(a, 4);
arr1[2] = 6;
arr1.print();
// Uncommenting the next line will cause an error
// because the index is out of bounds arr1[8] = 6;
const Array arr2(a, 4);
cout << arr2[2] << endl;
// Uncommenting the next line will cause an error
// because arr2 is const and cannot modify its elements
// arr2[2] = 7;
return 0;
}
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Vector in C++ STL C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted.Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template i
7 min read
Templates in C++ C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
C++ Interview Questions and Answers (2025) C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i
15+ min read
Operator Overloading in C++ in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot
8 min read
C++ Standard Template Library (STL) The C++ Standard Template Library (STL) is a set of template classes and functions that provides the implementation of common data structures and algorithms such as lists, stacks, arrays, sorting, searching, etc. It also provides the iterators and functors which makes it easier to work with algorith
9 min read
C++ Classes and Objects In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. We will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program.C++ ClassesA class is a user-defined data type, which holds its own data members and
9 min read