How to Implement a Const Function in C++ that Calls a Non-Const Update Function Without Making Class Variables Generally Mutable?

62 views Asked by At

I am working on a C++ project where I have a specific design challenge and I'm looking for advice on best practices. Here's the situation:

I have a class with a member function that I want to keep as const. This function needs to call another function (like a lazy update or similar) that is not const and is intended to modify some of the class's member variables. The update function's operation should be transparent to the user of the const function. Here's a simplified version of what I'm trying to achieve:

class MyClass {
public:
    void highLevelFunction() const {
        // This function should remain const
        updateData(); // This function modifies class state
    }

private:
    void updateData() {
        // Modify some state here
        data = newDataValue;
    }

    DataType data;
};

My objective is to maintain the logical constness of highLevelFunction(), but since it indirectly modifies the class state through updateData(), I'm not sure how to keep data non-mutable for the rest of the class. I want to avoid making data mutable because it should not be generally modifiable by all const functions.

Here are my specific questions:

  1. Is there a design pattern or C++ language feature that allows a const function to indirectly modify certain class members without making these members universally mutable?
  2. How can I ensure that only highLevelFunction() has the ability to modify data through updateData(), while keeping data protected from modifications in other const member functions?
  3. Are there any best practices or alternative approaches in C++ that I should consider to maintain const-correctness while allowing this kind of controlled mutability?

I am aware const-cast but was wondering if there are better design patterns to use!

Any insights or suggestions on how to approach this problem would be greatly appreciated!

0

There are 0 answers