15.4. Ensuring That a Member Function Doesn’t Modify Its Object
Problem
You need to invoke member
functions on a const object, but your
compiler is complaining that it can’t convert the type of object you are operating from
const
type to type.
Solution
Place the const keyword to the right of the member
function declaration in both the class declaration and definition. Example 15-4 shows how to do this.
Example 15-4. Declaring a member function const
#include <iostream>
#include <string>
class RecordSet {
public:
bool getFieldVal(int i, std::string& s) const;
// ...
};
bool RecordSet::getFieldVal(int i, std::string& s) const {
// In here, you can't modify any nonmutable data
// members (see discussion)
}
void displayRecords(const RecordSet& rs) {
// Here, you can only invoke const member functions
// on rs
}Discussion
Adding a trailing const to a member declaration and
its definition forces the compiler to look more carefully at what that member’s body is
doing to the object. const member functions are not
allowed to invoke any nonconst operation on data
members. If one does, compilation fails. For example, if, in RecordSet::getFieldVal, I updated a counter member, it wouldn’t compile
(assume that getFieldCount_ is a member variable of
RecordSet):
bool RecordSet::getFieldVal(int i, std::string& s) const {
++getFieldCount_; // Error: const member function can't modify
// a member variable
// ...
}It can also help catch more subtle errors, similar to how const works in its variable-qualifier ...