I am writing C++ code, and ran into a case where I wish to overload the square bracket operator for my class. From various sources, I find that you usually make two methods to do this, one with the const keyword, and one without the const keyword, but with an ampersand (&) before the method name. An example is given below.
int MyClass::operator[](unsigned int i) const {
return this->values[i];
}
int & MyClass::operator[](unsigned int i) {
return this->values[i];
}
My questions are as follows:
- Why do I have two methods, one with the
constkeyword, and one without it? - What does the ampersand (
&) in my second method do? - Why can I set a value at a given index using square brackets, when none of my methods are setters, and which of these two methods is invoked when I set a value?