access subclass functions

Steven Schveighoffer schveiguy at yahoo.com
Thu Nov 20 04:56:11 PST 2008


"Saaa" wrote
> Is this not possible, or am I doing anything wrong?
>
> Fruit[2] fruits; // Fruit has no peel function
>
> fruit[0]= new Apple();
> fruit[1]= new Banana(); //Banana has a protected peel() function returning 
> a bool
>
> bool b;
> b=fruit[1].peal();
>
> Error: no property 'peel' for type 'project.fruitclass.Fruit'
> Error: function expected before (), not 1 of type int
> Error: cannot implicitly convert expression (cast(Banana)1()) of type 
> 'project.banana.Banana' to bool

I think you have a typo in your example (and your example doesn't reflect 
the error messages), 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();

-Steve 




More information about the Digitalmars-d-learn mailing list