mutable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • arnaudk
    Contributor
    • Sep 2007
    • 425

    mutable

    What exactly does the keyword 'mutable' mean? It seems that both const and non-const functions can be called on mutable members. But that seems to defeat the very purpose of const...
  • RRick
    Recognized Expert Contributor
    • Feb 2007
    • 463

    #2
    Mutable means to be able to "change" the value.

    A const method can access a mutable value and use the value, but a const method can not change that value. Only non-const methods can change a value

    BTW: This better not be some exam question. You have been around here long enough to know that you are not suppose to post those questions.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      mutable means that the member can be changed even if the object is const.

      Like a linked list node:
      [code=cpp]
      class Node
      {
      Data* theData;
      Node* prev;
      Node* next;
      };
      [/code]

      If the Node object is const, you can't change the next/prev pointers. That means you can't have linked list of const Node objects. To avoid this, tou make the next/prev members mutable. It's your way of saying that the nest/prev members are not part of the "const-ness" of the object:

      [code=cpp]
      class Node
      {
      Data* theData;
      mutable Node* prev; //OK to change using a const object
      mutable Node* next;
      };
      [/code]


      Of course, you can abuse this but if you play ball using the rules, this is a pretty good way to do things.

      Comment

      • arnaudk
        Contributor
        • Sep 2007
        • 425

        #4
        I understand. Thanks!
        (BTW, I'm teaching myself C++ in my spare time and don't intend to sit any exams at this stage.)

        Comment

        Working...