Re: storing creature type


[ Follow Ups ] [ Post Followup ] [ CS2704 Web Discussion Board ] [ FAQ ]

Posted by John Kugelman on April 14, 2001 at 16:46:06:

In Reply to: storing creature type posted by Michael on April 14, 2001 at 15:20:36:

Michael wrote:

In the spec it says that we cant store the creature type. How are we supposed to output it then?

By having properly overridden virtual functions—polymorphism—the creatures should themselves know what type they are. What is forbidden is having some function outside the inheritance hierarchy "knowing" the objects' types. You can do something like this:

Animal *animal;

...

animal->printName ();

Here someAnimal points to some child class of Animal, which has a virtual function printName. You see how the caller doesn't know the type of the animal? If printName is overridden properly the right version will be called automatically, and the animal will "know" what type it is.

What you cannot do is something like this:

Animal *animal;

...

switch (animal->type ())
{
    case browser: say ("I'm a browser!"); break;
    case grendel: say ("I'm a grendel!"); break;
}

This is forbidden because now the caller has to know the type of the animal, which defeats the whole purpose of using polymorphism.

(Note: I probably wouldn't write my code like the first example, but you should get the idea of how polymorphism is applicable.)




Follow Ups:



Post a Followup

Name:
E-Mail:

Subject:

Comments:

Optional Link URL:
Link Title:
Optional Image URL:


[ Follow Ups ] [ Post Followup ] [ CS2704 Web Discussion Board ] [ FAQ ]