fork download
  1. #include <cstdlib>
  2. #include <typeinfo>
  3. #include <ctime>
  4. #include <iostream>
  5. #include <list>
  6.  
  7. class Animal
  8. {
  9. public:
  10. virtual ~Animal() = 0 ;
  11. };
  12.  
  13. Animal::~Animal() {}
  14.  
  15. class Cat : public Animal
  16. {
  17. };
  18.  
  19. class Dog : public Animal
  20. {
  21. };
  22.  
  23. typedef std::list<Animal*> list_type;
  24.  
  25. void displayTypes(list_type::iterator beg, list_type::iterator end)
  26. {
  27. while (beg != end)
  28. {
  29. Animal* value = *beg++;
  30.  
  31. if (typeid(*value) == typeid(Cat))
  32. std::cout << "Cat";
  33. else if (typeid(*value) == typeid(Dog))
  34. std::cout << "Dog";
  35. else if (typeid(*value) == typeid(Animal))
  36. std::cout << "Animal"; // This should never happen!
  37. else
  38. std::cout << "Unknown";
  39.  
  40. std::cout << '\n';
  41. }
  42. }
  43.  
  44. int main()
  45. {
  46. std::srand(std::time(0));
  47.  
  48. list_type list;
  49.  
  50. for (unsigned i = 0; i < 10; ++i)
  51. list.push_back((rand() % 2 ? (Animal*)new Cat : (Animal*)new Dog));
  52.  
  53. displayTypes(std::begin(list), std::end(list));
  54.  
  55. while (!list.empty())
  56. {
  57. delete list.back();
  58. list.pop_back();
  59. }
  60. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Cat
Dog
Dog
Cat
Dog
Cat
Dog
Cat
Dog
Cat