Caminhoneiro

c++ virtual e polimorf

Jan 4th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. using namespace std;
  2.  
  3. class Animal{
  4.    
  5.     public:
  6.         void getFamily() { cout << "We are animals" << endl; }
  7.    
  8.         virtual void getClass() { cout << "I'm an Animal" << endl;} //Permits polymorphism
  9. };
  10.  
  11. class Dog : public Animal{
  12.  
  13.     public:
  14.         getClass() {cout << "I'm a dog" << endl;}
  15.  
  16. };
  17.  
  18. class GermanShepard : public Dog{
  19.  
  20.     public:
  21.         void getClass() {   cout << "Im a german Shepard" << endl; }
  22.         void getDerived() { cout << "Im derived dog" << endl;}
  23.  
  24. }
  25.  
  26. void whatClassAreYou(Animal *animal){
  27.  
  28.     animal.getClass();
  29.    
  30.     /*THIS CLASS DO THE SAMETHING FROM THIS REFS INSIDE MAIN()
  31.    
  32.     Animal *animal = new Animal;
  33.     Dog *dog = new Dog;
  34.    
  35.     animal->getClass();
  36.     dog.->getClass();
  37.    
  38.     */
  39. }
  40.  
  41.  
  42. int main(){
  43.    
  44.     Animal *animal = new Animal;
  45.     Dog *dog = new Dog;
  46.    
  47.     animal->getClass();
  48.     dog.->getClass();
  49.    
  50.     //BOTH GONNA PRINT ANIMAL CLASS UNLESS THE ANIMAL CLASS METHOD getClass() is VIRTUAL!!!
  51.     whatClassAreYou(animal);
  52.     whatClassAreYou(dog);
  53.     //BOTH GONNA PRINT ANIMAL CLASS UNLESS THE ANIMAL CLASS METHOD getClass() is VIRTUAL!!!
  54.  
  55.    
  56.     Dog spot; //Dog object
  57.     GermanShepard max; //GermanShepard object
  58.    
  59.    
  60.     Animal* ptrDog = &spot;
  61.     Animal* ptrGShepard = &max;
  62.    
  63.     ptrDog -> getFamily();
  64.    
  65.     ptrDog -> getClass();
  66.    
  67.     ptrGShepard -> getFamily();
  68.    
  69.     ptrGShepard -> getClass();
  70.    
  71.    
  72.     return 0;
  73.  
  74. }
Add Comment
Please, Sign In to add comment