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

I have a member variable, enabled_mwhose value depends on a number of variables. Since these invariants must be supported 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 actually I want the user to foo_tgo through the class to change enabled_m. If the user just wants to read enabled_m, this should be a valid operation:

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

Is there a way to do enabled_m publicfor operations constand privatefor operations without const, without requiring the user to go through access procedures?

+4
source share
3

, . private ; const .

(, const const_cast), - . , , , .

+9

, , , - :

class AccessControl
{
private:
    int dontModifyMeBro;
public:
    const int& rDontModifyMeBro;
    AccessControl(int theInt): dontModifyMeBro(theInt), rDontModifyMeBro(dontModifyMeBro)
    {}

    // The default copy constructor would give a reference to the wrong variable.
    // Either delete it, or provide a correct version.
    AccessControl(AccessControl const & other): 
        dontModifyMeBro(other.rDontModifyMeBro), 
        rDontModifyMeBro(dontModifyMeBro)
    {}

    // The reference member deletes the default assignment operator.
    // Either leave it deleted, or provide a correct version.
    AccessControl & operator=(AccessControl const & other) {
        dontModifyMeBro = other.dontModifyMeBro;
    }
};
+10

, , .

is_enabled :

if (f.is_enabled())
    f.set_this(whatever);

, set_this, ( ) , , , :

if (!f.set_this(whatever))
   // deal with error

, ( ), . , , , , - enabled is_enabled set_this.

, , , . .

+5

All Articles