Potentially stupid newbie question

Steven Schveighoffer schveiguy at yahoo.com
Fri Aug 1 13:19:35 PDT 2008


"Mr. Red" wrote
> Hi.  You might say I'm kind of a greenhorn programmer... I had just begun 
> to settle into C++ when I found out about D.  As such I understand the 
> basics of OOP, inheritance and that kind of thing, but there's one thing I 
> can't figure out.  Say I have a base class Cat.  Then I have derived 
> (non-nested) classes Tiger, Leopard, and Lion, all just derived from the 
> base class Cat.  Then in my program, I want to have an array of Cats to 
> keep track of them all, and at any one point in the program the exact 
> species could change.  Now, I've tested and found that:
>
> Cat cat[10];
>
> cat[0] = new Tiger();
> cat[1] = new Leopard();
> cat[2] = new Lion();
> cat[3] = new Lion();
>
> ...
> And so on and so forth, compiles, but I'm not able to access the member 
> functions of the derived class, even if I've set them to public.  What 
> would I do if I wanted to access the member functions?  I know that this 
> is probably something simple... Is there perhaps a better way to do what 
> I'm trying to do then the array approach?

When you say "access the member functions," are these functions that Cat 
defines?  or functions only defined by the derived types?

If the former, they should be accessible through the Cat type.  i.e.:


class Cat
{
   void makeNoise() {writefln("meow");}
}

class Tiger
{
   void makeNoise() {writefln("growl");}
}

class Lion
{
   void makeNoise() {writefln("roar");}
}

cat[0].makeNoise(); // outputs growl
cat[2].makeNoise(); // outputs roar

If the latter, you need to downcast to the derived type.  i.e.:

Tiger t = cast(Tiger)cat[0]; // if cat[0] is not a Tiger, t will be null
if(t !is null)
  t.doTigerThing();
Lion L = cast(Lion)cat[0];
...

-Steve 





More information about the Digitalmars-d mailing list