fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <typeinfo> // for typeid
  4.  
  5. class Animal
  6. {
  7. public:
  8.  
  9. virtual void yawn() = 0;
  10. };
  11.  
  12. class Cat : public Animal
  13. {
  14. public:
  15.  
  16. void scratchTheLivingHellOutOfYou()
  17. {
  18. std::cout << "*scratch*\n";
  19. }
  20.  
  21. virtual void yawn() { std::cout << "meoyawnn!\n"; }
  22. };
  23.  
  24. class Tiger : public Cat
  25. {
  26. public:
  27.  
  28. virtual void yawn() { std::cout << "RAWR\n"; }
  29.  
  30. };
  31.  
  32. // EXPECTED OUTPUT:
  33. // *scratch*
  34. // RAWR
  35. // *scratch*
  36. // meoyawnn!
  37. int main(int argc, char* argv[])
  38. {
  39. std::vector<Animal*> animals;
  40. animals.push_back(new Cat);
  41. animals.push_back(new Tiger);
  42.  
  43. std::cout << "USING TYPEID\n\n\n";
  44.  
  45. // loop through the vector
  46. for(auto i = animals.begin(); i != animals.end(); ++i)
  47. {
  48. Animal* animal = *i;
  49.  
  50. // if it's a cat
  51. if(typeid(Cat) == typeid(*animal))
  52. {
  53. // make the cat scratch you
  54. Cat* cat = static_cast<Cat*>(animal);
  55. cat->scratchTheLivingHellOutOfYou();
  56. }
  57.  
  58. // make the animal yawn
  59. animal->yawn();
  60. }
  61.  
  62. std::cout << "\n\n\nUSING DYNAMIC_CAST\n\n\n";
  63.  
  64. // loop through the vector
  65. for(auto i = animals.begin(); i != animals.end(); ++i)
  66. {
  67. Animal* animal = *i;
  68.  
  69. // if it's a cat
  70. if(Cat* cat = dynamic_cast<Cat*>(animal))
  71. {
  72. // make the cat scratch you
  73. cat->scratchTheLivingHellOutOfYou();
  74. }
  75.  
  76. // make the animal yawn
  77. animal->yawn();
  78. }
  79.  
  80. return 0;
  81. }
Success #stdin #stdout 0s 3064KB
stdin
Standard input is empty
stdout
USING TYPEID


*scratch*
meoyawnn!
RAWR



USING DYNAMIC_CAST


*scratch*
meoyawnn!
*scratch*
RAWR