S
Stuart Golodetz
JKop said:Here's what I'm getting at:
Why would you cast a Dog* to a Mammal*? as in:
Mammal restt = new Dog;
delete restt;
Suppose you've got a list of mammals, and you want them all to (say) jump up
and down and shout "Wahey!" (Clearly all mammals do this on a regular
basis...) You don't want to store separate lists of cats and dogs, you just
want to store mammals. (For a more sensible example, consider storing a list
of controls, - you don't care whether it's a drop-down box, a button, or
whatever, all you're interested in is the fact that when you click on it it
does something.) Consider the following (rather odd ) bit of code:
#include <iostream>
#include <list>
class Mammal
{
public:
virtual void JumpUpAndDownAndShoutWahey() = 0;
virtual ~Mammal()
{
std::cout << "Bye!\n";
}
};
class Dog : public Mammal
{
public:
virtual void JumpUpAndDownAndShoutWahey()
{
std::cout << "I am a dog and I say 'Wahey!'\n";
}
virtual ~Dog()
{
std::cout << "Woof!\n";
}
};
class Cat : public Mammal
{
public:
virtual void JumpUpAndDownAndShoutWahey()
{
std::cout << "I am a cat and I also say 'Wahey!'\n";
}
virtual ~Cat()
{
std::cout << "Miaow!\n";
}
};
int main()
{
std::list<Mammal*> mammalList;
mammalList.push_back(new Dog);
mammalList.push_back(new Cat);
for(std::list<Mammal*>::iterator it=mammalList.begin(),
iend=mammalList.end(); it!=iend; ++it)
{
(*it)->JumpUpAndDownAndShoutWahey();
delete *it; // deleting an instance of a derived class through a
base class pointer - virtual destructor required in the base class or
behaviour is undefined
}
mammalList.clear();
return 0;
}