The subscript operator (Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
[]) is a postfix operator used to access elements of an array, a pointer to contiguous memory, or a user-defined container. In its built-in form, it is syntactic sugar for pointer arithmetic and dereferencing.
Built-in Mechanics
For built-in types, the expressionE1[E2] is strictly evaluated as *((E1) + (E2)). According to the C++ standard, one of the expressions must be a pointer to a completely-defined object type (or an array that decays to a pointer), and the other must be of an unscoped enumeration or integral type.
Because addition is commutative, the subscript operator is also commutative for built-in types.
Operator Overloading
For user-defined types,operator[] can be overloaded to provide custom indexing semantics.
Overloading Rules:
- It must be implemented as a member function. It cannot be a free (non-member) function. As of C++23, it may be implemented as a
staticmember function; prior to C++23, it was strictly required to be a non-static member function. - It typically returns an lvalue reference (
T&) to allow the expression to be used on the left side of an assignment. - It is standard practice to provide both a
constand a non-constoverload to support mutable and read-only access depending on the constness of the object instance. - Prior to C++23, it must accept exactly one parameter. The parameter can be of any type (e.g.,
std::stringfor associative containers).
C++23 Multidimensional Subscript Operator
Starting with C++23, the subscript operator can accept zero or multiple arguments, enabling direct multidimensional indexing without relying on chained operators (e.g.,[][]) or the function call operator (()).
Master C++ with Deep Grasping Methodology!Learn More





