hqt

Polymorphism

hqt
Nov 25th, 2012
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include "grade.h"
  2. #include <iostream>
  3. #include <vector>
  4. #include <iostream>
  5. using namespace std;
  6.  
  7.  
  8. class Animal
  9. {
  10. public:
  11.     virtual void sound() { cout << "i'm an animal" << endl;}
  12. };
  13.  
  14. class People : public Animal
  15. {
  16. public:
  17.     void sound() { cout << "I'm a people" << endl;}
  18.     void loving() { cout << "I can love" << endl;}
  19. };
  20.  
  21. int main()
  22. {
  23.     vector<Animal*> world;
  24.     Animal* animal = new Animal();
  25.     Animal* people = new People();  
  26.    
  27.     animal->sound();    // i'm an animal
  28.     people->sound();    // i'm a people
  29.    
  30.     /*CANNOT*/
  31.     // people->loving(); // because i'm an animal, i cannot love :(
  32.    
  33.     /* no error: because both animal and people are "animal" */
  34.     world.push_back(animal);
  35.     world.push_back(people);
  36.    
  37.     People* realPeople = new People();
  38.     realPeople->sound();
  39.     realPeople->loving();       // Ah, now i can love :x    
  40.     world.push_back(realPeople);
  41.     //world[2]->loving(); // NOOOO, I cannot love :( because everyone now sees me as an real animal :((
  42.    
  43. }
Advertisement
Add Comment
Please, Sign In to add comment