Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

index.cpp for polymorphism

By: a guest on Nov 4th, 2012  |  syntax: C++  |  size: 0.85 KB  |  views: 41  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. }
clone this paste RAW Paste Data