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:
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.
Answers to questions are automatically generated and may not have been reviewed.
Discover operator overloading, allowing us to define custom behavior for operators when used with our custom types
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course