Why are both these functions not const?

The purpose of this code is to return a value @ location [i] in a valarray of doubles (ArrayDb is an alias for valarray<double>)

1
2
3
4
5
6
7
8
9
double & Student::operator[](int i)
{
    return ArrayDb::operator[](i);
}

double Student::operator[](int i) const
{
    return ArrayDb::operator[](i);
}


If in both cases the purpose is to not modify data, only retrieve data at a given point, why then is the first function not

double & Student::operator[](int i) const

What is it about returning a reference that doesn't require me to declare the member function as const? I feel like I'm missing something pretty obvious but this code is bugging the heck out of me not seeing why.

If you want to return a reference from that method and have the method be const, then you need to return a const reference:

const double & Student::operator[](int i) const

Otherwise, the caller would be able to modify the Student's internals through the non-const reference, thus breaking the const contract.
Last edited on
Topic archived. No new replies allowed.