i would like to run a function method of a class inside another function method of another class. I wrote the following code as an example and it compiles and return the expected values. My question is if this is the correct way of preforming a computation of class method inside another class method…
Regards
#include <iostream>
class CBoo {
public:
CBoo();
void Test();
void Plot();
private:
int b;
};
CBoo::CBoo() {
b = 3;
}
void CBoo::Test() {
b++;
}
void CBoo::Plot() {
std::cout << "b: " << b << std::endl;
}
class CFoo {
public:
CFoo();
void Test( CBoo &Boo );
void Plot();
private:
int a;
};
CFoo::CFoo() {
a = 3;
}
void CFoo::Test( CBoo &Boo ) {
for ( int i = 0 ; i < 10 ; i++ ) {
a++;
Boo.Test();
}
}
void CFoo::Plot() {
std::cout << "a: " << a << std::endl;
}
int main( ) {
CFoo Foo;
CBoo Boo;
Foo.Test( Boo );
Foo.Plot();
Boo.Plot();
return 0;
}
There are two straightforward ways to do this. One of them, the one you chose, is to pass an external class object to another object method. The other is to encapsulate an object inside of another object and to call it directly from a method of the enclosing class.
There may be more esoteric ways of doing this, but the one you chose is perfectly reasonable. Which option you choose is based on the architecture of your program.