The Wayback Machine - https://web.archive.org/web/20241121142120/https://www.geeksforgeeks.org/overloading-subscript-or-array-index-operator-in-c/
Open In App

Overloading Subscript or array index operator [] in C++

Last Updated : 02 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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;
}

Output
a
a

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;
}

Output
512
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 [].

  1. Overloading of [] may be useful when we want to check for index out of bound.
  2. 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;
}

Output
1 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;
}

Output
1 2 6 5 
4




Similar Reads

Operator Overloading '<<' and '>>' operator in a linked list class
Prerequisite: Operator Overloading in C++, Linked List in C++ C++ comes with libraries that provide ways for performing Input and Output. In C++, Input and Output are performed as a sequence of bytes, also known as streams. Input and Output stream are managed by the iostream library. cin and cout are the standard objects for the input stream and ou
4 min read
C++ | Operator Overloading | Question 10
Which of the following operator functions cannot be global, i.e., must be a member function. (A) new (B) delete (C) Conversion Operator (D) All of the above Answer: (C) Explanation: new and delete can be global, see following example. #include #include #include using namespace std; class Myclass { int x; public: friend void* operator new(size_t siz
1 min read
Increment (++) and Decrement (--) Operator Overloading in C++
Operator overloading is a feature in object-oriented programming which allows a programmer to redefine a built-in operator to work with user-defined data types. Why Operator Overloading? Let's say we have defined a class Integer for handling operations on integers. We can have functions add(), subtract(), multiply() and divide() for handling the re
4 min read
C++ program to compare two Strings using Operator Overloading
Pre-requisite: Operator Overloading in C++Given two strings, how to check if the two strings are equal or not, using Operator Overloading. Examples: Input: ABCD, XYZ Output: ABCD is not equal to XYZ ABCD is greater than XYZ Input: Geeks, Geeks Output: Geeks is equal to Geeks Approach: Using binary operator overloading. Declare a class with a string
3 min read
Matrix operations using operator overloading
Pre-requisite: Operator OverloadingGiven two matrix mat1[][] and mat2[][] of NxN dimensions, the task is to perform Matrix Operations using Operator Overloading.Examples: Input: arr1[][] = { {1, 2, 3}, {4, 5, 6}, {1, 2, 3}}, arr2[][] = { {1, 2, 3}, {4, 5, 16}, {1, 2, 3}} Output: Addition of two given Matrices is: 2 4 6 8 10 22 2 4 6 Subtraction of
13 min read
C++ Logical (&&, ||, !) Operator Overloading
Prerequisites: OperatorsOperator Overloading Logical operators are used for combining two or more conditions or constraints or to complement the evaluation of the original condition in consideration. The result returns a Boolean value, i.e., true or false. In C++, there are 3 logical operators: Logical AND (&&): This operator returns true o
3 min read
C++ Bitwise Operator Overloading
Prerequisites: Operator OverloadingBitwise Operator in C/C++ In C++, there are a total of six bitwise operators. The six bitwise operators are bitwise AND (&), bitwise OR (|), bitwise XOR (^), left shift (<<), right shift (>>), and bitwise NOT (~). The & (bitwise AND) in C++ takes two numbers as operands and does AND on every bi
7 min read
Typecast Operator Overloading in C++
In C++, the typecast operator can be overloaded to customize the behavior of casting operators to define how user-defined data types can be converted into other types. This enables developers to define how instances of a class are converted to other types, providing more control over implicit type conversions. By overloading typecast operators, dev
6 min read
Overloading New and Delete operator in c++
The new and delete operators can also be overloaded like other operators in C++. New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.If overloading is done out
5 min read
Operator overloading in C++ to print contents of vector, map, pair, ..
Operator overloading is one of the features of Object oriented programming which gives an extra ability to an operator to act on a User-defined operand(Objects). We can take advantage of that feature while debugging the code specially in competitive programming. All we need to do is to overload the stream insertion operator(See this article to unde
3 min read
Rules for operator overloading
In C++, following are the general rules for the things that are not allowed with operator overloading. 1) Only built-in operators can be overloaded. New operators can not be created. 2) Arity of the operators cannot be changed. 3) Precedence and associativity of the operators cannot be changed. 4) Overloaded operators cannot have default arguments
3 min read
Different Ways of Operator Overloading in C++
In C++, operator overloading is the concept that allows us to redefine the behavior of the already existing operator for our class. C++ provides a special function called operator function that can be used to achieve operator overloading. In this article, we will learn the different ways in which we can define the operator function for operator ove
6 min read
Error: std::endl is of Unknown Type when Overloading Operator <<
In C++, the << operator is commonly overloaded for custom output for user-defined types using streams. However, an issue may arise when using std::endl with an overloaded operator<<. It is shown as the type of std::endl being unknown, leading to compilation errors. In this article, we will learn the cause of this issue and how can we re
4 min read
C++ Assignment Operator Overloading
Prerequisite: Operator Overloading The assignment operator,"=", is the operator used for Assignment. It copies the right value into the left value. Assignment Operators are predefined to operate only on built-in Data types. Assignment operator overloading is binary operator overloading.Overloading assignment operator in C++ copies all values of one
4 min read
Types of Operator Overloading in C++
C++ provides a special function to change the current functionality of some operators within its class which is often called as operator overloading. Operator Overloading is the method by which we can change some specific operators' functions to do different tasks. Syntax: Return_Type classname :: operator op(Argument list){ Function Body} // This
4 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 overload in C++. C++ Operator OverloadingC++ has
9 min read
deque::operator= and deque::operator[] in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::operator= This operator
4 min read
Why overriding both the global new operator and the class-specific operator is not ambiguous?
The below section deals about overload resolution as it helps in the fundamentals of overloading and overriding. Predict the output: C/C++ Code #include <iostream> using namespace std; class Gfg { public: void printHello() { cout << "hello gfg-class specific" << endl; } }; void printHello() { cout << "hello gf
5 min read
vector::operator= and vector::operator[ ] in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::operator=This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new
4 min read
Queries for number of distinct elements from a given index till last index in an array
Given a array ‘a[]’ of size n and number of queries q. Each query can be represented by a integer m. Your task is to print the number of distinct integers from index m to n i.e till last element of the array. Examples: Input: arr[] = {1, 2, 3, 1, 2, 3, 4, 5}, q[] = {1, 4, 6, 8} Output: 5 5 3 1 In query 1, number of distinct integers in a[0...7] is
6 min read
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of th
9 min read
Advantages and Disadvantages of Function Overloading in C++
Function overloading is one of the important features of object-oriented programming. It allows users to have more than one function having the same name but different properties. Overloaded functions enable users to supply different semantics for a function, depending on the signature of functions. Advantages of function overloading are as follows
3 min read
Input/Output Operators Overloading in C++
Operator Overloading is a part of Polymorphism, which enables the feature because of which we can directly use operators with user-defined classes and objects. To read more about this, refer to the article operator overloading in C++. Input/Output Operators(>>/<<) Overloading in C++ We can't directly use the Input/Output Operators (>
2 min read
Function overloading and const keyword
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading
5 min read
Overloading stream insertion (<>) operators in C++
In C++, stream insertion operator "<<" is used for output and extraction operator ">>" is used for input. We must know the following things before we start overloading these operators. 1) cout is an object of ostream class and cin is an object of istream class 2) These operators must be overloaded as a global function. And if we want to
2 min read
Function Overloading and float in C++
Although polymorphism is a widely useful phenomena in C++ yet it can be quite complicated at times. For instance consider the following code snippet: C/C++ Code #include&lt;iostream&gt; using namespace std; void test(float s,float t) { cout &lt;&lt; &quot;Function with float called &quot;; } void test(int s, int t) { cout
2 min read
Function Overloading vs Function Overriding in C++
Function Overloading (achieved at compile time) Function Overloading provides multiple definitions of the function by changing signature i.e. changing number of parameters, change datatype of parameters, return type doesn’t play any role. It can be done in base as well as derived class.Example: void area(int a); void area(int a, int b); C/C++ Code
3 min read
Function Overloading and Return Type in C++
Function overloading is possible in C++ and Java but only if the functions must differ from each other by the types and the number of arguments in the argument list. However, functions can not be overloaded if they differ only in the return type. Why is Function overloading not possible with different return types and identical parameters? Function
2 min read
Does overloading work with Inheritance?
If we have a function in base class and another function with the same name in derived class, can the base class function be called from derived class object? This is an interesting question and as an experiment, predict the output of the following C++ program: [GFGTABS] C++ #include <iostream> using namespace std; class Base { public: int f(
5 min read
Function Overloading in C++
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading
4 min read
Practice Tags :
three90RightbarBannerImg