0Pricing
C++ Academy · Lesson

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

  1. Arithmetic and Comparison Operators
  2. Stream Insertion and Extraction Operators
  3. Subscript and Function Call Operators
  4. Three-Way Comparison Operator C++20
← Back to C++ Academy