C/C++ Arena

Step 4 of 5

operator[]

operator[] lets your type be indexed like an array: obj[i]. It must be a member function. Two versions are usually provided:

T& operator[](int i);               // for non-const objects: allows obj[i] = x
const T& operator[](int i) const;   // for const objects: read-only

Returning a reference is what makes assignment through it work.

#include <iostream>
#include <string>

class Week {
public:
    std::string& operator[](int day) { return plans_[day - 1]; }
    const std::string& operator[](int day) const { return plans_[day - 1]; }

private:
    std::string plans_[7] = {"gym", "", "", "", "", "", "rest"};
};

void show(const Week& w) {
    std::cout << w[1] << ", " << w[3] << ", " << w[7] << "\n";
}

int main() {
    Week w;
    w[3] = "swim";
    show(w);
}
gym, swim, rest

Custom indexing

The operator is a normal function, so it can translate the index. Week uses days 1 to 7 (as people count them) and converts to array positions 0 to 6 inside. The conversion lives in one place.

Const overloads

show receives a const Week&, so only the const version of operator[] can be called; it returns a const std::string&, so w[1] = "x" inside show wouldn't compile. main has a non-const Week, so it gets the version that allows writing. The compiler picks the right one automatically.

Like [] on arrays and std::vector, operator[] usually doesn't check the index (that's what .at() is for in the standard library).

Your turn: give Loadout an operator[] taking a slot number 1 to 5 (not 0 to 4!) and returning the weapon name in that slot.

Previous: Printing with operator<< Next: operator< and sorting