c++ - Access out of scope variables without passing them? -


is there way access variables outside class?

class myclass1 { public:     int x; };  class myclass2 { public:     int get_x()     {         //somehow access myclass1's variable x without          //passing argument , return it.     } }  int main() {     myclass1 obj1;     obj1.x = 5;     myclass2 obj2;     std::cout << obj2.get_x();     return 0; } 

one of main things making me reluctant split programs many small organized classes rather few messy huge ones hassle of passing every single variable 1 class might need another. being able access variables without having pass them (and having update both declarations , definitions should change) convenient , let me code more modually.

any other solutions issue appreciated, suspect there may dangerous trying access variable way.

the way can access x of myclass1 if have instance of class, because x not static.

class myclass2 { public:     myclass2(myclass1* c1) : myc1(c1) {}     int get_x()     {         return myc1->x;     } private:     myclass1* myc1; } 

then can use like

int main() {     myclass1 obj1;     obj.x = 5;     myclass2 obj2{&obj1};     std::cout << obj2.get_x();     return 0; } 

Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -