Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 756
fbrereto Avatar asked Nov 28 '22 07:11

fbrereto


1 Answers

Most engineers will prefer that you use accessor methods, but if you really want a hack-around, you could do something like this:

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;
    }
};
like image 129
iwolf Avatar answered Dec 10 '22 11:12

iwolf