RAII: Initializing data member in const method

Posted by Thomas Matthews on Stack Overflow See other posts from Stack Overflow or by Thomas Matthews
Published on 2010-03-19T16:31:54Z Indexed on 2010/03/19 17:31 UTC
Read the original article Hit count: 260

In RAII, resources are not initialized until they are accessed. However, many access methods are declared constant. I need to call a mutable (non-const) function to initialize a data member.

Example: Loading from a data base

struct MyClass
{
  int get_value(void) const;

  private:
     void  load_from_database(void); // Loads the data member from database.

     int m_value;
};

int
MyClass ::
get_value(void) const
{
  static bool value_initialized(false);
  if (!value_initialized)
  {
    // The compiler complains about this call because
    // the method is non-const and called from a const
    // method.
    load_from_database();
  }
  return m_value;
}

My primitive solution is to declare the data member as mutable. I would rather not do this, because it suggests that other methods can change the member.

How would I cast the load_from_database() statement to get rid of the compiler errors?

© Stack Overflow or respective owner

Related posts about c++

Related posts about const-correctness