Search code examples
c++member-access

How to access a class member variable from a different class in c++


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?


Solution

  • A few options:

    1. 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

    2. Have B inherit from A. Then you can access A::f(variable2) from B::g

    3. Have an instance of A as a member of B. You then access A::f(variable2) from that instance.

    4. 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.