Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2021
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. class Animal {
  4. public:
  5.     Animal(const char * name) : name(name) {};
  6. private:
  7.     const char * name;
  8. };
  9.  
  10. class Dog : public Animal {
  11. public:
  12.     Dog(const char * name) : Animal(name) {};
  13.    
  14.     void Pet() { // here the function is called on the dog abstraction
  15.         Petted(); // dynamically dispatched to the run-time type.
  16.     }
  17. protected:
  18.     virtual void Petted() {
  19.         std::cout << "You petted a random Dog!" << std::endl;
  20.     }
  21. private:
  22. };
  23.  
  24. class Snoopy : public Dog {
  25.     bool is_tired;
  26. public:
  27.     Snoopy() : Dog("Snoopy") {};
  28.  
  29. protected:
  30.     virtual void Petted() {
  31.         if (is_tired) {
  32.             std::cout << "You petted Snoopy but he is tired" << std::endl;
  33.         } else {
  34.             std::cout << "You petted Snoopy!" << std::endl;
  35.             std::cout << "Snoopy: Bark Bark!";
  36.         }
  37.     }
  38. };
  39.  
  40. void pet_a_dog(Dog* dog) { // here we can reference Dog*
  41.     dog->Pet(); // pet a Dog* but resolved to Snoopy.
  42. }
  43.  
  44. int main() {
  45.     Dog* snoopy = new Snoopy();
  46.    
  47.     pet_a_dog(snoopy);
  48.    
  49.     delete snoopy;
  50.    
  51.     return 0;
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement