constness can be considered as addional level of type information and therefore we can overload methods in C++ based on only const properties. const-ness of a function should capture the abstract state of the object and not the physical bit state. Following class has 2 overloaded methods which differ only in the const-ness. Remember, subscript operators, if you need one you need the other.
class Fred { ... };
class MyFredList {
public:
const Fred& operator[] (unsigned index) const; // first
Fred& operator[] (unsigned index); // second
...
};
A const object invokes first method therefore after returning the reference to internal data structure, you can not modify as it is const. A non const object invokes the second memeber function in which you can indeed modify returned Fred object. While returning references to internal data structure either return a const reference or return by value if you don't want it to be modified.
An exhaustive information on const-correctness is here:
http://www.parashift.com/c++-faq-lite/const-correctness.html
class Fred { ... };
class MyFredList {
public:
const Fred& operator[] (unsigned index) const; // first
Fred& operator[] (unsigned index); // second
...
};
A const object invokes first method therefore after returning the reference to internal data structure, you can not modify as it is const. A non const object invokes the second memeber function in which you can indeed modify returned Fred object. While returning references to internal data structure either return a const reference or return by value if you don't want it to be modified.
An exhaustive information on const-correctness is here:
http://www.parashift.com/c++-faq-lite/const-correctness.html
Comments