[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppMutable
When in a class, when you see the following member function:
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:
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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;
}
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
