Krice <pa****@mbnet.fikirjutas:
There is a component class inside the host class:
class Host
{
Component *c;
...
In some cases Component needs to call the host and
I guess the only way is that you pass the host for it:
Component::Component(Host *h)
{
h->Do_Something();
...
Somehow I think this is bad design, but how to avoid it?
In the component constructor it is quite easy to avoid, as suggested by
Daniel - just use a factory function for creating the components, which
additionally calls Host::Do_Something() before or after the construction
as appropriate.
The situation gets more complicated if the component needs to call host
also later, from other member functions. By some reason (probably bad
design) I have had many such cases. Just passing the host pointer as you
show above, this is actually not so bad. What would be worse is to store
the host pointer or reference inside the component object. This could
potentially create a whole bunch of maintenance and lifetime issues. As a
simple solution, one could just pass the host pointer each time the
component needs it.
A side note: I would probably use a reference instead of a pointer here,
as most probably the Host object should remain alive throughout the call.
And yes, as other posters mentioned, it might be a good idea to restrict
the amount of interdependencies by passing a pointer or reference to a
narrower interface instead of the full host (interface = ABC, host
derived from the interface).
hth
Paavo