I'm not sure to entirely understand the philosophy behind the const keyword used on class methods.
I've always thought that using the const keyword in the signature of a class method meant that this method would not modify the fields of the object it's called on. However when we use for example a vector, there is an overload for operator [] that is not const :
whateverT & vector<whateverT>::operator [] ( size_t pos )
No matter what you do with the reference you are given, it will perform no modifications on the vector's fields, even if the referenced item is modified.
Another example :
template<class T> class Array
{
T * _items;
T & operator [] ( size_t pos ) const
{
return _items[ pos ];
}
}
I can use the const keyword here because the value of _items is not modified (no matter what we do with what it points to). For the compiler this is correct, but if i access one of the items and modify it, the operator [] will allow the modification of the array even though it's supposed to be const, i.e supposed not to modify the "
contents "
of the array.
What should be done in that kind of case ? Use or don't use the const keyword ?
Thank you :)