access subclass functions

Saaa empty at needmail.com
Thu Nov 20 05:14:57 PST 2008


>
> I think you have a typo in your example
:)
> (and your example doesn't reflect the error messages),
How do you mean? Like not at all?
As you noticed it isn't the actual code, but I thought it would reflect it 
though.

> but that isn't the problem.
>
> In a strongly typed language, you cannot access subclass functions that 
> aren't defined in the base class unless you are sure the instance is of 
> the subclass type.
>
> to fix, you should do this:
>
> if(auto ban = cast(Banana)fruit[1])
>  ban.peel();
>
> the if(auto ban = ...) ensures that fruit[1] is a Banana.  If you are sure 
> it will always be a banana (i.e. the cast doesn't return null), you can 
> do:
>
> (cast(Banana)fruit[1]).peel();
Yay, thanks!
Now that you mention it, I think I've had this problem before :/
even though it is really logical, thx again.

In stead of numbers I use an enum, which makes it really difficult to get 
this wrong:
fruits[BANANA].peel();
:D
Now that I got this out of the way I see peel() should be public. 




More information about the Digitalmars-d-learn mailing list