c++ - How to make inaccessible class variable -


i'm wondering if possible make class variable inaccessible inside class? way change value of variable through class setter. example:

class foo { private:     int m_var;     bool m_isbig;     void setvar(int a_var)     {         // before setting value, emitting signal         m_var = a_var;     }     void method()     {         int copy = m_var; // ok         m_var = 5; // error!         setvar(101); // ok         dosomething();     }     void dosomething()     {         if(m_var > 5)         { m_isbig = true; }         else         { m_isbig = false; }     } }; 

i know write class setters , getter, don't have access other methods/vars class foo(encapsulation!). think common problem, , there design pattern this, can't found any.

edit: edited code clear, want in setter.

i'm not aware of pattern this, 1 possibility wrap member inside nested class. think better style, since creation of new type expresses intent member not integer, but, instead, has unique behaviour.

class foo {     class mvar {       public:         mvar(foo* parent, int value = 0) : m_parent(parent), m_value(value) {}         mvar& operator=(const mvar&) = delete; // disable assignment         operator int() const { return m_var; }         void set(int new_value) {             // something, possibly m_parent             // nested classes have access parent's private members             m_value = new_value;         }       private:         foo* m_parent;         int m_value;     } m_var;     void method() {         int copy = m_var; // ok         m_var = 5;        // error         mvar.set(101);    // ok     } }; 

this doesn't want, since m_var doesn't really have type int, it's consider.


Comments