Advertisement
chzchz

Untitled

Mar 28th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4.  
  5. using namespace std;
  6.  
  7. class Animal {
  8.  public:
  9.   Animal(const string& type) : type_(type) {}
  10.  
  11.   void Eat(const string& fruit) {
  12.     cout << type_ << " eats " << fruit << endl;
  13.   }
  14.  
  15.   virtual void Sound() const = 0;
  16.  
  17.  private:
  18.   const string type_;
  19. };
  20.  
  21.  
  22. class Cat : public Animal {
  23.  public:
  24.   Cat() : Animal("cat") {}
  25.  
  26.   void Sound() const override {
  27.     cout << "Meow!" << endl;
  28.   }
  29. };
  30.  
  31.  
  32. class Dog : public Animal {
  33.  public:
  34.   Dog() : Animal("dog") {}
  35.  
  36.   void Sound() const override {
  37.     cout << "Whaf!" << endl;
  38.   }
  39. };
  40.  
  41.  
  42. class Parrot : public Animal {
  43.  public:
  44.   Parrot(const string& name) : Animal("parrot"), name_(name) {}
  45.  
  46.   void Sound() const override {
  47.     cout << name_ << " is good!" << endl;
  48.   }
  49.  
  50.  private:
  51.   const string& name_;
  52. };
  53.  
  54.  
  55. class Horse : public Animal {
  56.  public:
  57.   Horse() : Animal("horse") {}
  58.  
  59.   void Sound() const override {
  60.     cout << "some sound" << endl;
  61.   }
  62. };
  63.  
  64.  
  65. void MakeSound(const Animal& a) {
  66.   a.Sound();
  67. }
  68.  
  69. int main() {
  70.   vector<shared_ptr<Animal>> animals{
  71.       make_shared<Cat>(),
  72.       make_shared<Dog>(),
  73.       make_shared<Parrot>("Kesha"),
  74.       make_shared<Horse>(),
  75.   };
  76.  
  77.   for (auto a : animals) {
  78.     MakeSound(*a);
  79.   }
  80.  
  81.   return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement