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?
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;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With