Kip Irvine home page | C++ Book Page
The mutable qualifier allows a single member of a class to remain non-const, even when the enclosing class object is const-qualified. According to [Stroustrup94:287], the mutable qualifier was introduced to C++ to reduce the necessity for casting away const in real-world C++ applications. Studies have found that this result was achieved in approximately 50% of the cases.
In the following example, the Student object is const-qualified, but we are still able to set the lastViewingDate field of the mutable Transcript object within the Student:
class Transcript { public: Transcript() { } void SetLastViewingDate( long date ); }; class Student { public: Student() { } Transcript & GetTranscript() const; void SetStudentID( long id ); private: long studentID; mutable Transcript trans; }; void main() { long today; const Student S; //S.SetStudentID( 1111111 ); //error: cannot modify const // The following expression is valid: S.GetTranscript().SetLastViewingDate( today ); }