Guest User

Untitled

a guest
Jan 23rd, 2021
15
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. class Animal {
  4. public:
  5. Animal(const char * name) : name(name) {};
  6. virtual ~Animal() {}
  7. private:
  8. const char * name;
  9. };
  10.  
  11. class Dog : public Animal {
  12. public:
  13. Dog(const char * name) : Animal(name) {};
  14. virtual ~Dog() {}
  15.  
  16. void Pet() {
  17. std::cout << "Petted a dog!" << std::endl;
  18. }
  19. private:
  20. };
  21.  
  22. class Cat : public Animal {
  23. public:
  24. Cat(const char * name) : Animal(name) {};
  25. virtual ~Cat() {}
  26.  
  27. void Pet(){
  28. std::cout << "Petted a cat!" << std::endl;
  29. }
  30. };
  31.  
  32. class Snoopy : public Dog {
  33. public:
  34. Snoopy() : Dog("Snoopy") {};
  35. virtual ~Snoopy() {}
  36.  
  37. void Pet() {
  38. std::cout << "Petted snoopy!" << std::endl;
  39. }
  40. };
  41.  
  42. class Garfield : public Cat {
  43. public:
  44. Garfield() : Cat("Garfield") {};
  45. virtual ~Garfield() {}
  46.  
  47. void Pet() {
  48. std::cout << "Petted a garfield!" << std::endl;
  49. }
  50. };
  51.  
  52. void pet(Animal* animal) {
  53. if (dynamic_cast<Cat*>(animal)) {
  54. if (dynamic_cast<Garfield*>(animal)) {
  55. Garfield* garfield = (Garfield*)animal;
  56. garfield->Pet();
  57. } else {
  58. Cat* cat = (Cat*)animal;
  59. cat->Pet();
  60. }
  61. } else if (dynamic_cast<Dog*>(animal)) {
  62. if (dynamic_cast<Dog*>(animal)) {
  63. Snoopy* snoopy = (Snoopy*)animal;
  64. snoopy->Pet();
  65. } else {
  66. Dog* dog = (Dog*)animal;
  67. dog->Pet();
  68. }
  69. }
  70.  
  71. }
  72.  
  73. int main() {
  74. Cat* garfield = new Garfield();
  75. pet(garfield);
  76. delete garfield;
  77. return 0;
  78. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×