Who`s Afraid to Be Const Correct? Reading Const Correctly in C++ - Const Member Functions
(Page 5 of 6 )
Another use of const not available in C, but very useful in C++, is the possibility to declare member functions const. This means that you are promising that the member function won’t change the value of any of the data members of the object.
Imagine what would happen when the function membersize() of some class List would change the order of elements in that list while you were iterating through it! By declaring the memberconst it is guaranteed that this cannot happen, and it will force any other programmer that will be maintaining that code not to touch the member values either.
The declaration of a constant member functionsize() looks like this:
size_t size() const;
You will find them most often used when a class doesn’t expose its data members in the public interface [Meyers]. Such a class will provide ‘get’ and ‘set’ functions in its public interface, and since it makes sense for something that reads out a value not to change that value (or any other values in the object that is being accessed), you will notice ‘get’ functions declared as constant member functions.
A const member function guarantees that an object’s data members will remain untouched, so these functions can only be invoked on a const object. Member functions can behave differently depending on whether they are declared const or not. They can be overloaded exactly for this purpose. That is why you will find two implementations of ‘operator[ ]’ in the STL std::vector class:
// returns a const reference to an element you can only read
const_reference operator[](size_type _Pos) const
{ // subscript nonmutable sequence
return (*(begin()+_Pos));
}
// returns a reference to an element you can manipulate
reference operator[](size_type _Pos)
{ // subscript mutable sequence
return (*(begin()+_Pos));
}
Next: Right There Right Now >>
More C++ Articles
More By J. Nakamura