Skip to main content
The subscript operator ([]) 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 expression E1[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.
The built-in operator does not perform bounds checking. Accessing an index outside the allocated memory range results in undefined behavior.

Operator Overloading

For user-defined types, operator[] can be overloaded to provide custom indexing semantics. Overloading Rules:
  1. 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 static member function; prior to C++23, it was strictly required to be a non-static member function.
  2. It typically returns an lvalue reference (T&) to allow the expression to be used on the left side of an assignment.
  3. It is standard practice to provide both a const and a non-const overload to support mutable and read-only access depending on the constness of the object instance.
  4. Prior to C++23, it must accept exactly one parameter. The parameter can be of any type (e.g., std::string for 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 (()).
Tired of Poor C++ Skills? Fix That With Deep Grasping!Learn More