Guest User

Untitled

a guest
Jan 22nd, 2021
52
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. 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.  
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.

×