Overloading the Subscript Operator
How can I overload the subscript operator []
for my custom type?
To overload the subscript operator []
for your custom type, you need to define a member function named operator[]
. This function should take an index parameter and return a reference to the element at that index.
Here's an example of overloading the subscript operator for a custom Vector
class:
#include <iostream>
class Vector {
private:
float elements[3];
public:
float& operator[](int index) {
return elements[index];
}
const float& operator[](int index) const {
return elements[index];
}
};
int main() {
Vector v;
v[0] = 1.0f;
v[1] = 2.0f;
v[2] = 3.0f;
std::cout << v[1] << "\n";
}
2
In this example, we define two overloads of the operator[]
function:
- One for non-const objects, which returns a non-const reference to the element.
- One for const objects, which returns a const reference to the element.
This allows us to use the subscript operator to access and modify elements of our Vector
object, just like we would with a built-in array.
Operator Overloading
Discover operator overloading, allowing us to define custom behavior for operators when used with our custom types