On Saturday, 20 December 2014 at 15:40:32 UTC, Derix wrote:
So, I have this pet project where classes Cat and Dog inherit
from the more generic Beast class.

All beasts prosper and multiply and so do cats and dogs. The
breeding routine is fairly constant across species, with minor
variations. So I'd like to define the "breed" method in the Beast
class and overload it in the Cat and Dog classes.

Something like :

Cat rita = new Cat(female);
Cat ringo= new Cat(male);
Cat junior=rita.breed(ringo);

with

Class Cat:Beast{
...
        Cat breed(Cat sire){
                // do what all beasts do

                //then add cat-specific genetics
        }
...
}       

Now, what I can't seem to figure out is the "// do what all beast
do" part. "this" current object is obviously an instance of the
Cat class. How do I de-specialize it so it can behave as an
instance of the more generic Beast class ? Then, the offspring
will in turn be an instance of Beast : how to cast it as a Cat ?

So far, all I've been able to do is to dance around the issue by
writting ad-hoc constructors like

Beast b=new Beast( someCat )

or

Cat c=new Cat(someBeast)

but this seems awkward and inefficient.

There must be some more clever and straightforward way to do
this, surely ?

Also : D is not my first OO language, but polymorphism and
inheritance still are advanced concepts for me.

What you do is to implement the "breed" method in Beast class, then override it in both Cat and Dog, but then call "super.breed()" method which belongs to Beast.

Reply via email to