0

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!

3
  • 3
    In your description, you didn't mention the mutable keyword that exists in C++. If the data members are an implementation detail that is not exposed to the outside world, then possibly consider making the class member(s) in question mutable. See this Commented Dec 24, 2023 at 2:56
  • 3
    A const class method can only call other const methods. The End. There are no exceptions or workarounds to this rule. A const function, by definition, cannot modify its class. That's what makes it a const function. Commented Dec 24, 2023 at 2:59
  • One question per post. How to call a non-const function within a const function and How to call a non-const method from a const method? Commented Dec 24, 2023 at 3:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.