I have the following 2 class header files (A.h and B.h), with a function inside each:
class A { public: double f(double); };
class B { public: double g(double); };
Here are their corresponding cpp files:
include "A.h"
double A::f(double variable1)
{
// do stuff on variable 1
}
include "B.h"
include "A.h"
double B::g(double variable2)
{
// do stuff on variable2 using f from A
}
I would like to use function f (from A) inside function g (in B). How do I do this?
A few options:
Make the functions
static. You can do that if the functions don't use any non-static members of the class. Then you can callA::f(variable2)withinB::gHave
Binherit fromA. Then you can accessA::f(variable2)fromB::gHave an instance of
Aas a member ofB. You then accessA::f(variable2)from that instance.Pass an instance of
Ainto the functionB::g. Access the function via that instance.(1) works well if the classes serve little more than acting as a way of bundling related functions together. (Although I prefer to use a
namespacefor such cases.)(2) works well if the inheritance structure is logical. Don't do it if it isn't.
(3) is a common thing to do.