Search code examples
c++operator-overloading

Issue with Assignment Operator and Array Subscription operators


I am trying to overload subscription operator and faced with some issue
for example my class is E, what I did at first is:

int E::operator[](int n){
    if(n<length && n>0)
        return data[n];
    else
        return 0;

}

let say I have an object of E ( A ), and I want to return the A[0]. this operator works fine.
the second thing I wanted to do is if I want to do A[0] = 4.
what I need to implement here? assignment operator? or subscription operator?


Solution

  • Commonly the subscript operator is written with two overloads: One to read and one to write. This allows you to read in const contexts:

    Write overload:

    int& E::operator[](size_t index)
    {
        if( index >= lenght )
            throw std::out_of_range("Subscript out of range");
        else
            return data[n];
    }
    

    Read overload: (Note that is const cualified)

    int E::operator[](size_t index) const
    {
        if( index >= lenght )
            throw std::out_of_range("Subscript out of range");
        else
            return data[n];
    }