We help IT Professionals succeed at work.

mutable types

VEngineer asked
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.
Watch Question

This one is on us!
(Get your first solution completely free - no credit card required)

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.  

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.

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;

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".

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;

mprao, have you read the question history?

Binder already answered the queston!

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.

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.



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.

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

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.


Thanks for all the comments - I wish the policy would stop being such a big issue in each question (hint, hint EE).
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.