I define two versions of overloaded operator[] function in a class array. ptr is a pointer to first element of the array object.
int& array::operator[] (int sub) {
return ptr[sub];
}
and
int array::operator[] (int sub) const {
return ptr[sub];
}
Now, if I define a const object integer1 the second function can only be called….. but if I make a non-const object and then invoke as below:
cout << "3rd value is" << integer1[2];
which function is called here?
In your second example, the non-const version will be called, because no conversion is required, and a call that requires no conversion is a better match than one that requires a conversion.
Ultimately, however, you have a basic problem here: what you really want is behavior that changes depending on whether you’re using your object as an rvalue or an lvalue, and
constdoesn’t really do that. To make it work correctly, you normally want to return a proxy object, and overloadoperator=andoperator Tfor the proxy object:Now we get sane behavior — when/if our
array<int>(or whatever type) is const, ouroperator[] constwill be used, and it’ll give aconst proxy. Since its assignment operators are not const, attempting to use them will fail (won’t compile).OTOH, if the original
array<int>was not const, we’ll get a non-const proxy, in which case we can use bothoperator Tandoperator=, and be able to both read and write the value in thearray<int>.