Search code examples
c++c++11constantsmember-variables

Is it possible to specify a private member variable public only for const operations?


I have a member variable, enabled_m, whose value is dependent on a number of variables. Since these invariants should be maintained by the class, I want it to be private:

class foo_t
{
public:
    void set_this(...); // may affect enabled_m
    void set_that(...); // may affect enabled_m
    void set_the_other_thing(...); // may affect enabled_m

    bool is_enabled() const { return enabled_m; }

private:
    bool enabled_m;
};

Which works, but really my intent is to require a user of foo_t to go through the class to modify enabled_m. If the user wants to just read enabled_m, that should be an allowable operation:

bool my_enabled = foo.enabled_m; // OK
foo.enabled_m = my_enabled; // Error: enabled_m is private

Is there a way to make enabled_m public for const operations and private for non-const operations, all without having to require a user go through accessor routines?


Solution

  • No, there's no way to restrict modification only to members. private restricts all access to the name; const prevents modification everywhere.

    There are some grotesque alternatives (like a const reference, or use of const_cast), but the accessor function is the simplest and most idiomatic way to do this. If it's inline, as in your example, then its use should be as efficient as direct access.