In several of my books the mutable
example uses a non-const member function incorrectly as was pointed out by Paul
Ezust (see for example C++ for C Programmers:3rd edition p156.) The indicated
change corrects the problem. The following code is a small variation on the book
that incorporates the correction.
#include < iostream >
#include < string >
using namespace std;
class person {
public:
person(const string n, int a, const unsigned long ss)
:name(n), age(a), soc_sec(ss){}
void bday() const {++age;} //had been non-const
void print() const
{
cout << name << " is " << age
<< " years old with SSN " << soc_sec << endl;
}
private:
const string name;
mutable int age;
const unsigned long soc_sec;
};
int main()
{
const person ira("ira pohl", 38, 1110111UL);
ira.print();
ira.bday();
ira.print();
}