[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppMutable

mutable

C++ keyword enabling you to to have const member functions that DO change your class member variables.

When in a class, when you see the following member function:

//Declaration
double getValue() const;
//Definition
double MyClass::getValue() const
{
  return mValue;
}


you know its a function that does not alter the member variables or the class.

But imagine that getting this value is a very time-intensive process. Then you might want the class to also store the amount of times this function has been called. Then you have two options:
  • make the member function non-const
  • make the member variable mutable

Example using mutable

class MyClass
{
  //Stuff..
  mutable int mRequests;
  double getValue() const;
  //More stuff..
}

double MyClass::getValue() const
{
  ++mRequests; //A member variable
  return mValue;
}


Example using non-const member function

class MyClass
{
  //Stuff..
  int mRequests;
  double getValue();
  //More stuff..
}

double MyClass::getValue()
{
  ++mRequests; //A member variable
  return mValue;
}




last edited (August 4, 2005) by bilderbikkel, Number of views: 1594, Current Rev: 1

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.