Access variables between classes

Hello,

I am newbie in C++ and I am sorry if this question was already answered.

I have two classes. First class manages variables and second class draws them on screen.
Something like this:

  
  
//=== first class ===  
class calculate_variables {  
	public:  
	void calculate();  
	  
	int MyVariable;  
};  
  
void calculate_variables::calculate(){  
	//Do something with MyVariable  
}  
  
//=== second class ===  
class draw_info{  
	public:  
	draw();  
};  
  
void draw_info_info::draw(){  
	font.drawString(ofToString(((calculate_variables*)ofGetAppPtr())->MyVariable), X, Y);  
}  
  
//=== testApp ===  
class testApp : public ofBaseApp{  
	public:  
	calculate_variables CalculateVariables;  
	draw_info DrawInfo;  
};  
  
void testApp::update(){  
	CalculateVariables.calculate();  
}  
void testApp::draw(){  
	Drawinfo.draw();  
}  
  

Am I doing this the right way? ((myClass*)ofGetAppPtr())->someVar works fine but should I use something else like firend class? If yes, how would I need to change my code?

Any ideas? Thanks!

you can access variables between classes (objects) if they are visible in the same scope by doing

name_of_instance + . or -> if it is a pointer + name_of_var

so… in your case

  
CalculateVariables.MyVariable;  

in order to pass them inside the other class you can use either a public var in your draw_info class that will be equaled to the MyVariable

**draw_info.myVar = CalculateVariables.MyVariable;
**

or use a “setter-getter” function…

**draw_info.setVar(CalculateVariables.MyVariable);
**

or just make draw function of draw_info class able to accept the variable:

**void draw(int var){

mydravar = var;

//mydravar used by stuff
}
**
and in the testapp.cpp::draw()

**dra_info.draw(CalculateVariables.MyVariable);
**
But here is the problem…

you are doing it wrong. using two classes is overkilling in this case

you can have your draw function inside calculate_variables class and have them communicate without having to pass values between classes

also worths to mention … the lazy way… :: you can declare them as globals and access them anyway… …but don’t do that.

1 Like

you could also add a pointer to the calculate_variables instance as class member to draw_info, and then get to CalculateVariables->MyVariable that way.

1 Like

Thank you very much! That helped me alot.