tags:

views:

109

answers:

1

I have a class which looks something like this:

class MyClass
{
public:
  // some stuff omitted

  /*** 
    A function which, in itself, is constant and doesn't change the class
  ***/
  void myFunction( void ) const;
private:
  /***
    If loaded is true, then internal resources are loaded
  ***/
  boolean loaded;
};

Because I designed my class this way I am forced to do this:

MyClass :: myFunction( void ) const
{
  if( !loaded )
  {
     // do something here

     loaded = true; /** <-- this violates const **/
  }

  // carry out some computation
}

Because I need to set loaded flag the function now violates const qualifier.

I have a lot of code that stores constant objects and it will be time consuming to go round and change them to non-const. Moreover, this will be slightly hacky since I really want the objects to be const.

What is the best way to refactor my class in order to keep myFunction constant?

P.S. The resources guarded by loaded are required only for several functions and therefore loading them in advance is not a very good solution.

+11  A: 

Use the mutable keyword.

class MyClass
{
public:
  void myFunction( void ) const;
private:
  mutable boolean loaded;
};

This says that the loaded member should be treated as being logically const but that physically it may change.

anon
Oh my... Thank you. I knew there was an embarassingly easy solution to this.
sneg
+1: Never knew this but needed it many times. (I used slow pointer-solution [bool *loaded => pointer never changes but value behind pointer can] or dirty cast solution.
rstevens