A naive (straightforward) solution is to simply pass a reference to A
to constructors for both B
and C
:
class B
{
public:
B (const A& a) : mA (a) {}
private:
const A& mA;
};
Or maybe better yet, pass references to the fields you actually need:
class B
{
public:
B (const int& foo, const std::string& bar) : mFoo (foo), mBar (bar) {};
private:
const int& mFoo;
const std::string mBar;
};
But the fact that the problem at hand leads me to this kludgy straightforward solution is a code smell. I suspect that the entire design is broken.
I wonder what A
's real purpose really is? Is it simply to be a holder for a B
and a C
? Does it have a job? Is it trying to do too much?
Or maybe the problem is in the opposite direction. Maybe in an attempt to squeeze every single thing in to an object-shaped box, you have created a machine that is more complicated than it needs to be. Should B
's and C
's tasks really be the responsibility of A
? Or perhaps even (gasp) free functions?