Have you heard of "mutable" keyword?

Questions by suji   answers by suji

Showing Answers 1 - 8 of 8 Answers

Lily

  • Sep 28th, 2005
 

Mutable data members can be modified by const member functions.

The mutable 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.

SEE FOLLOWING CODE :-

********************************************

class Mutable
{
private :
              int m_iNonMutVar;
 mutable   int m_iMutVar;

public:
  Mutable();
  void TryChange() const;

};

Mutable::Mutable():m_iNonMutVar(10),m_iMutVar(20)  {};

void Mutable::TryChange() const
{
     m_iNonMutVar  = 100; // THis will give ERROR
     m_iMutVar       = 200; // This will WORK coz it is mutable
}
*****************************************

Any query pls write at mohit.gonduley@gmail.com

erahul.ag

  • Jul 2nd, 2010
 

Answer are correct but not perfect.

The Crux is:
Purpose of 'mutable' is not changing some member's values of a const object at all. (Its a side bug which comes free with functionality.)
You may use mutable for:
1) Reference counter
2) Appling mutexes
3) Storing some heavy evaluation objects.

Please refer:
highprogrammer . com/alan/rants/mutable . html

Rdgs..
Rahul

  Was this answer useful?  Yes

vladatzar

  • Oct 29th, 2010
 

The mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const.
You cannot use the mutable specifier with names declared as static or const, or reference members.


  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions