Start New Discussion within our Software Development Community

I'm looking for the best way to make a method available to a sub class (not talking inheritance, polymorphism at all, just standalone classes!) without handing down a million pointers to each sub class.

Class A;   // contains many instances of other classes.
Class Z;   // one of those many classes hidden deep within Class A.
Class Bar; // sexy, desirable class.

Class Foo {
public: 
   Bar *getBar() { return m_Bar; }; // get pointer to m_Bar
private:
   Bar *m_Bar; // perhaps allocated at some point, or pointed at an existing "Bar"
   A   m_A; 
};

In one of "m_A" 's methods, one of it's members (a Class Z instance, completely unrelated to Foo, unaware of it's existance) would like access to the current instance of "m_Bar".

Depending on how deep m_Z is in m_A, this would require passing a pointer down and down and down into A's heirarchy, from A's constructor (e.g., m_A(Bar*)), all the way through each contained class (B(Bar*), C(Bar*), D(Bar*) ... ...), finally to Z.

This can be a horror story if the original pointer is de-allocated, etc. at some point.

Is the correct way to make *m_Bar accessible to any deeply contained sub class, to make Foo a Singleton class?

i.e., so deep in m_A, an instance of m_Z has a method that would call

Z::Z_Function() {
   Foo::Instance()->getBar();
}

I know this would 'work', but it limits me to one Foo class only. I know I must be missing a very obvious way to get around this that doesn't involve singletons. :(

What exactly is this program? Why do you need all this interconnected access? This sounds like a very long series of very bad design decisions...

This article has been dead for over six months. Start a new discussion instead.