Potentially stupid newbie question

JAnderson ask at me.com
Sat Aug 2 00:56:20 PDT 2008


Nick Sabalausky wrote:
> "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). 
> 

Just to add to what has already been said.  You might want to research 
interfaces.  Interfaces have no concrete body and people who inherit 
from it must implement all of is functions.  They are often the better 
way to force the general shape of a type.  By shape I mean that it will 
fit into things (functions etc...) that take that shape.  At which point 
the concept of polymorphic becomes more powerful because you can re-use 
many patterns with different implementations and structures.

-Joel



More information about the Digitalmars-d mailing list