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


i have following 2 class header files (a.h , b.h), function inside each:

class { public: double f(double); };

class b { public: double g(double); };

here corresponding cpp files:

include "a.h"

double a::f(double variable1) { // stuff on variable 1 } 

include "b.h"

include "a.h"

double b::g(double variable2) { // stuff on variable2 using f } 

i use function f (from a) inside function g (in b). how do this?

a few options:

  1. make functions static. can if functions don't use non-static members of class. can call a::f(variable2) within b::g

  2. have b inherit a. can access a::f(variable2) b::g

  3. have instance of a member of b. access a::f(variable2) instance.

  4. pass instance of a function b::g. access function via instance.

(1) works if classes serve little more acting way of bundling related functions together. (although prefer use namespace such cases.)

(2) works if inheritance structure logical. don't if isn't.

(3) common thing do.


Comments