Re: composite
bob@blah.com wrote:
we are using the composite pattern which simply has a common abstract
base class. Deriving from this class there is a Comp class, and a
CompItem class, say. i.e.
abstractBase
\
\
v \
Comp CompItem
|
|
V
CompItemSubClass
We have also the CompItemSubClass.
Now we can either have pointers to CompItems or CompItemSubClasses. I
want to be able to call the correct function (without dynamic casting
if possible).
e.g.
virtual void toto (CompItem* compItem);
virtual void toto (CompItemSubClass* compItemSubClass);
we have something like this;
CompItem* tmp=someFunc(); // creates either a CompItems
orCompItemSubClass
then I do;
toto(tmp);
which always invokes;
virtual void toto (CompItem* compItem);
Is there any nifty way to have
virtual void toto (CompItemSubClass* compItemSubClass);
called without casting (assuming the tmp contains a pointer to a
CompItemSubClass) ?
Thanks much. Hope that makes sense. I'm rushing here :)
There is no direct way. If you know that the object a pointer to
which you obtained from 'someFunc' is one of the two (and you are
sure of it), using a static cast would be OK. 'dynamic_cast' is
only needed if you're not sure and it also requires for the class
to be polymorphic (I don't think you mentioned whether it was).
A bit better way is to give the choice to the object itself. That
should essentially be an exercise in double dispatch:
class CompItem : public abstractBase {
...
virtual void callTotoFor(someOtherClass* ptr) {
ptr->toto(this);
}
};
class CompItemSubClass : public CompItem {
...
virtual void callTotoFor(someOtherClass* ptr) {
ptr->toto(this);
}
};
... // inside 'someOtherClass's member function or elsewhere
CompItem *pItem = someFunc();
// blah->toto(pItem); -- this doesn't work well, do:
pItem->callToto(blah);
HTH. Ask more questions as you get them.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask