Potentially stupid newbie question
Nick Sabalausky
a at a.a
Fri Aug 1 21:16:31 PDT 2008
"Mr. Red" <garfieldrules at sbcglobal.net> wrote in message
news:g6vv1i$1nu1$1 at digitalmars.com...
>I had been referring to when the methods were exclusive to the derived
>class, but considering that in my would-be program the derived classes
>mostly just redefine functions already present in the base class, the first
>method is better. I was just whipping up a quick test program with an
>unsophisticated hierarchy and didn't think to include the base class's
>version of the function too. Thank you for your help!
If you have an array of a base type (like Cat), it doesn't usually make much
sense to try to access things that only exist in a derived type. This is
because, for instance, you can be absolutely certain that "cat[someIndex]"
is going to be a Cat, but you have no idea if it's also a Tiger or a Lion or
whatever. So "someCat.doSomethingOnlyALionCanDo()" is risky business,
because what if "someCat" isn't a Lion? Just because you put a Lion into
myCat earlier in the program doesn't mean that later parts can be certain
that that happened and is still true.
Once in a while you will see cases where it's useful to say something like
"Is this cat a Lion? If it's a Lion, do this special Lion-only thing on it".
Polymorphism (ie: Steven's first part) is the usual/preferred way to handle
this, when possible. But once in a while you might come across cases where
that approach just isn't very applicable. In those cases, you can do RTTI
(Run-Time Type Identification, ie, Steven's second part).
More information about the Digitalmars-d
mailing list