mutable types

Posted on 2000-02-29
Last Modified: 2010-04-02
For the first time, I saw in some code a declaration like:

class C {
    mutable int x;
    mutable int y;

Can someone explain what a mutable is and what it's behavior is?  Thanks.
Question by:VEngineer
  • 5
  • 3
  • 2
  • +3

Accepted Solution

Binder earned 25 total points
ID: 2569574
From MSDN:

This keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.

LVL 22

Expert Comment

ID: 2569706
It just means that the data member can be "mutated", i.e. changed, from a constant member function.  

class C
  mutable int m;
  int i;
  void f() const // A constant function.
     m = 0;
     i = 0; // Error can't change from a const function.

This was a very late addition to the standard, so many compilers don't yet support it.  
LVL 22

Expert Comment

ID: 2569731
I should mention that it is used in cases where data member might be changed in such a way that the abstract type reprsented by an object might not change.  For example, if you have a fraction class that stores seperate numerator and denomenator values.  You can make the two nutable.  This would allow you to change numerator and denominator in a cosntant function, like to reduce the fraction to lowest denomenator if that is needed in a function, as long as that doesn't change the fraction reprented.
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

LVL 10

Expert Comment

ID: 2571342
mutables are memeber that are allowed to change in a const function. ie. modifying their values from within a const function is ok.

In the example you quote, this means that const members of class C can change the values of x or y.

Some uses for mutables might include:
* caching of data to avoid calculations
* reference counters
* 'hidden' links (eg. list of all object of a given class allocated).

Having a mutable sves you from either:
* declare what should be a 'const' function as not const just so you can change some member
* having to cast away the constness of a memeber variable explicitly like this
 const_cast<MyClass*>(this)->m_xxx = yyy;


Expert Comment

ID: 2571656
mutable keyword:

A keyword that enables a member variable to be changed by a const function.

If you want to update an "invisible" data member inside a "const" member function use "mutable", or use "const_cast".

A small percentage of inspectors need to make innocuous changes to data members

(e.g., a "Set" object might want to cache its last lookup in hopes of improving the performance of its next lookup). By saying the changes are "inocuous," I mean that the changes wouldn't be visible from outside the object's interface (otherwise the method would be a mutator rather than an inspector).

When this happens, the data member which will be modified should be marked as "mutable" (put the "mutable" keyword just before the data member's declaration; i.e., in the same place where you could put "const"). This tells the compiler that the data member is allowed to change during a const member function. If you can't use "mutable", you can cast away the constness of "this" via "const_cast". E.g., in "Set::lookup() const", you might say,

Set* self = const_cast<Set*>(this);

After this line, "self" will have the same bits as "this" (e.g., "self==this"), but "self" is a "Set*" rather than a "const Set*". Therefore you can use "self" to modify the object pointed to by "this".

Expert Comment

ID: 2582589
Mutable :
  To allow a class data member to be modified even though it is the data member of a const object , we can declare the data member as mutable.
 A mutable data member is a member that is never const, even when it is he data member of a const object.

for eg:

/* The following is a small program in which I am creating a const Object.
Now all the members of the object becomes constant . So the only way to assign value
to the member variable mem_of_a_2 of object a is through Initialization list
"const A a ={0,60};".Where the members are initialized when we create the object itself.
       Now if we try to assign value to the data member of the const object as in our case if
we try to assign value to data member of the const object a using "a.mem_of_a2 = 70;", the
compiler will give U an error "error C2166: l-value specifies const object".
     But since we have said that the data member mem_of_a_1 is mutable (can be changed - cannot be constant)
the compiler does not give us error*/

#include <iostream>
using namespace std;
class A
          mutable int mem_of_a_1;
        int mem_of_a_2;         /* *To make this program work make this data member also mutable */

void main()
      const A a ={0,60};    /* This is the only way to assign a value to mem_of_a2 data member */
      a.mem_of_a_1 = 54;    /* This works because we have made the data member Mutable (can be changed - cannot be constant) */    
      a.mem_of_a_2 = 70;    /* error C2166: l-value specifies const object */
      cout << a.mem_of_a_1<<endl;
      cout << a.mem_of_a_2<<endl;
LVL 22

Expert Comment

ID: 2582927
mprao, have you read the question history?

Binder already answered the queston!
LVL 10

Expert Comment

ID: 2585964
mproa - I dont think you've added anyhitng to what was already explained.  Hardly warrents being an answer.  Binder (or nietod) deserve the points on this.  I suggest you withdraw your answer and let these other experts receive their just rewards.


Expert Comment

ID: 2586331
I am sorry Binder. I should have added the text as comments . That was my first entry into the experts-exchange .I dint know how to make an entry.Instead of using comment I selected answer.
I will withdraw my answer. Binder U deserve the points.


LVL 22

Expert Comment

ID: 2587249
mprao, binder should have answered originally, which woudl have prevented the problem in the first place.  Sometimes experts don't answer because they aren't sure if they are right or just don't know if their answer is "good enough".  In that case, if the expert is right, you can post a comment to that effect and/or add more details if needed.  You should only answer if the previous comments were wrong.

Expert Comment

ID: 2587316
Hi nietod,
 Thanks for the information. Anyway I am sorry for the trouble caused .

LVL 22

Expert Comment

ID: 2587340
No problem.  Unfortunately, it is hard to tell the difference between the experts that don't know better and the ones that do, and do it anyways.  

The next version of EE will hopefully have a code of recommended behavior, maybe that will help.

Author Comment

ID: 2593973
Thanks for all the comments - I wish the policy would stop being such a big issue in each question (hint, hint EE).

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Create string splitting user defined function in C++ 23 303
Grammars for C C++ and java 1 122
How to convert MFC APP to Win32 APP. 19 80
Problem with SqlConnection 4 168
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question