C++ · Module 10 · Lesson 31 min read

Subscript, Call & Conversion Operators

Subscript operator[]

arduino
double& operator[](std::size_t i) { return data_[i]; }              // read/write
const double& operator[](std::size_t i) const { return data_[i]; }  // read-only on const objects

Return a reference so obj[i] = x works. Provide both const and non-const versions. C++23 allows multiple indexes: matrix[r, c].

Function call operator() → functors

csharp
struct Discount {
    double rate;
    double operator()(double price) const { return price * (1 - rate); }
};
Discount festival{0.1};
festival(500);   // 450 — the object is called like a function

Function objects (functors) can hold state (like rate) and are used everywhere in the STL: comparators, hash functions, predicates. Lambdas are a shortcut for writing them (Unit 14).

Conversion operators

csharp
class Percentage {
    double value_;
public:
    explicit operator double() const { return value_ / 100; }
    explicit operator bool() const { return value_ != 0; }
};

explicit matters ⚠️

  • Non-explicit conversion operators convert silently, which can cause surprising overloads and comparisons
  • explicit operator bool still works in conditions (if (obj), !obj, &&) — "contextual conversion" — but blocks int x = obj; ✅
  • Use explicit by default; that's how std::unique_ptr, std::optional and streams do it

Other overloadable operators

  • -> and unary *: smart pointers and iterators
  • =: assignment (next lessons)
  • new/delete: custom allocation (advanced)
  • User-defined literals: operator""_km lets you write 5.0_km

User-defined literals example

arduino
constexpr double operator""_km(long double v) { return static_cast<double>(v * 1000); }
double d = 2.5_km;   // 2500 metres

The standard library has some: "abc"s (string), 10ms (chrono), 5i (complex).

Example

C++
#include <chrono>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

class MonthlyBudget {
public:
    double& operator[](int month) { check(month); return amounts_[month - 1]; }             // write
    const double& operator[](int month) const { check(month); return amounts_[month - 1]; } // read
    explicit operator bool() const {                    // "is any budget set?"
        for (double a : amounts_) if (a > 0) return true;
        return false;
    }
private:
    static void check(int m) { if (m < 1 || m > 12) throw std::out_of_range("month must be 1-12"); }
    std::vector<double> amounts_ = std::vector<double>(12, 0.0);
};

struct Discount {                                         // a functor with state
    double rate;
    double operator()(double price) const { return price * (1 - rate); }
};

struct CountCalls {
    int calls = 0;
    void operator()(const std::string& msg) { ++calls; std::cout << "  log #" << calls << ": " << msg << '\n'; }
};

constexpr double operator""_km(long double v) { return static_cast<double>(v * 1000); }
constexpr double operator""_km(unsigned long long v) { return static_cast<double>(v * 1000); }

int main() {
    MonthlyBudget b;
    std::cout << std::boolalpha << "budget set? " << static_cast<bool>(b) << '\n';
    b[1] = 21000;
    b[11] += 25000;
    if (b) std::cout << "budget set! Jan = " << b[1] << ", Nov = " << b[11] << '\n';
    // double x = b;          // error: no implicit conversion
    // int n = b;             // error: operator bool is explicit
    try {
        b[13] = 1;
    } catch (const std::out_of_range& e) {
        std::cout << "error: " << e.what() << '\n';
    }

    Discount festival{ 0.15 };
    std::cout << "festival price of 2000: " << festival(2000) << '\n';

    CountCalls logger;
    logger("app opened");
    logger("expense added");
    std::cout << "logger was called " << logger.calls << " times\n";

    double trip = 2.5_km + 800;
    std::cout << "trip length: " << trip << " m, marathon: " << 42_km << " m\n";

    using namespace std::chrono_literals;
    auto timeout = 1500ms;
    std::cout << "timeout: " << timeout.count() << " ms = "
              << std::chrono::duration<double>(timeout).count() << " s\n";
    return 0;
}

/* Output:
budget set? false
budget set! Jan = 21000, Nov = 25000
error: month must be 1-12
festival price of 2000: 1700
  log #1: app opened
  log #2: expense added
logger was called 2 times
trip length: 3300 m, marathon: 42000 m
timeout: 1500 ms = 1.5 s
*/