aLLex aLLex - 1 month ago 8
C++ Question

How to access variables in different class from other class

x cannot be static

I'd like to have

class A{
static std::vector<C> vec_ca;
public:
int x = 6;
`};
class B{
std::vector<C> vec_cb;
public:
int x = 7;
};
class C
{
void foo(){
int k = x;
}
};


And k will be set depending of it class: if k in vec_ca k = 6; if k in vec_cb k = 7. Is it possible to be done?

Answer

There are two ways. You can use getter and setter methods like so:

class B{
 std::vector<C> vec_cb;
public:
  int get_x(){return x;}
private:
  int x = 7;
};

and call get_x from the other class. And one other way to accomplish this is using friend classes. So you can do:

class B{
 std::vector<C> vec_cb;
 friend class A;
private:
  int x = 7;
};
Comments