Subscript and Function Call Operators
Overload [] and () to make types behave like containers or callables.
operator[] — Indexed Access
Overload [] to make your type usable like an array. Useful for containers, matrices, image classes.
class Vec {
std::vector<double> data_;
public:
double& operator[](size_t i) { return data_[i]; }
double operator[](size_t i) const { return data_[i]; }
};Two Overloads: const and non-const
Provide both. Calling on a const instance dispatches to the const overload; non-const allows assignment.
All lessons in this course
- Arithmetic and Comparison Operators
- Stream Insertion and Extraction Operators
- Subscript and Function Call Operators
- Three-Way Comparison Operator C++20