Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading subscript operator []

Why does it require to be a member function of a class for its operation and is good to return a reference to private member?

class X
{
public:

    int& operator[] (const size_t);
    const int &operator[] (const size_t) const;

private:
    static std::vector<int> data;
};

int v[] = {0, 1, 2, 3, 4, 5};
std::vector<int> X::data(v, v+6);

int& X::operator[] (const size_t index)
{
    return data[index];
}

const int& X::operator[] (const size_t index) const
{
    return data[index];
}
like image 668
user963241 Avatar asked Mar 23 '26 17:03

user963241


1 Answers

  • As to why is it required to have [] as a member, you can read this question (by yours sincerely). Seems it's just the way it is with no really really convincing explanation.

  • As to why return reference? Because you want to provide a way not only to read, but also (for non-const objects) to modify the data. If the return weren't a reference (or some proxyr)

    v[i] = 4;

    wouldn't work.

HTH

like image 72
Armen Tsirunyan Avatar answered Mar 25 '26 07:03

Armen Tsirunyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!