Advertisement
Guest User

index.cpp for polymorphism

a guest
Nov 4th, 2012
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4. using namespace std;
  5.  
  6. class Animal {
  7.   public:
  8.     string name;
  9.     Animal (const std::string& givenName) : name(givenName) {
  10.  
  11.     }
  12.     string speak () {
  13.       return "";
  14.     }
  15.        
  16.   };
  17.  
  18. class Dog: public Animal {
  19.   public:
  20.     Dog (const std::string& givenName) : Animal (givenName) {
  21.  
  22.     }
  23.     string speak ()
  24.       { return "Woof, woof!"; }
  25.   };
  26.  
  27. class Cat: public Animal {
  28.   public:
  29.     Cat (const std::string& givenName) : Animal (givenName) {
  30.     }
  31.     string speak ()
  32.       { return "Meow..."; }
  33.   };
  34.  
  35. int main() {
  36.     std::vector<std::unique_ptr<Animal>> animals;
  37.     animals.push_back( new Dog("Skip") );
  38.     animals.push_back( new Cat("Snowball") );
  39.  
  40.     for( int i = 0; i< animals.size(); ++i ) {
  41.         cout << animals[i]->name << " says: " << animals[i]->speak() << endl;
  42.     }
  43.        
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement