John Dibling <dib@substitute_my_full_last_name_here.com> wrote in message
news:b1********************************@4ax.com...
On Mon, 14 Jul 2003 11:49:16 -0700, "Mike Wahler"
<mk******@mkwahler.net> wrote:
alg <al******@yahoo.com> wrote in message
news:mz*********************@bgtnsc05-news.ops.worldnet.att.net... Why is so necessary sometimes in C++ that you have to cast a pointerbetween a base object and a derived object?
Usually, it's because of a poor design.
One cannot make this claim categorically.
"Usually" isn't categorical.
It is often necesarry and
proper to cast, although I would agree that casts are easy to use
inappropriately. In COM programming for example, a very common
scenario is to have many objects which are similar in nature, but have
some unique prepoerties. For example, suppose you are writing stock &
option trading software. Your software might abstract common elements
in to an interface called IOrder, where attirbutes specific to stock
trades (such as ticker symbol) are in the derived interface
IStockOrder, and option-specific attributes (such as OPRA code and
expiration date) are in the derived interface IOptionOrder. Your
system would likely need to make available to clients an array of
"all" orders, in which case the array would be an array of IOrder*'s.
If you subscribe to the theory that casts are categorically wrong,
"Usually" isn't categorical.
then your only other option is to have one array for IStockOrder*'s
and another for IOptionOrder*'s. If this were the case, you must have
duplication of at least some code, which I would argue is much more
indicitave of a design flaw.
If I had to use members that belonged only to IStockOrder or IOptionOrder,
then I would probably have one collection of IStockOrder*, another of
IOptionOrder*, and perhaps another of the two mixed up in a collection of
IOrder*. I would use each collection as appropriate. The code would be
cast-free and would execute more efficiently. Ideally, everything would be
done polymorphically through a single collection of IOrder*, but if it can't
be then why use a collection of IOrder* if you are going to have to downcast
them all later?
One potential big problem with downcasts is where the project is large and
you have to add another type, which might force you to wade through all your
code, find all your downcasts, and possibly add another case for the added
type all over the place.
I don't see where the code duplication is in having separate collectoins.
You are doing different things with each collection. That's why they are
separate.
DW