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:
double A::f(double variable1)
{
// do stuff on variable 1
}
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 call A::f(variable2)
within B::g
Have B
inherit from A
. Then you can access A::f(variable2)
from B::g
Have an instance of A
as a member of B
. You then access A::f(variable2)
from that instance.
Pass an instance of A
into the function B::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 namespace
for 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.