Polymorphism via pointer - C++ Class

C++ examples for Class:Polymorphism

Description

Polymorphism via pointer

Demo Code

#include <iostream> 
   /*from   w  ww  .  j  a  va2  s . com*/
class Pet 
{ 
public: 
    Pet():age(1) {  } 
    ~Pet() { } 
    virtual void speak() const { std::cout << "Pet speak!\n"; } 
protected: 
    int age; 
}; 
   
class Dog : public Pet 
{ 
public: 
    void speak() const { std::cout << "Woof!\n"; } 
}; 
   
class Cat : public Pet 
{ 
public: 
    void speak() const { std::cout << "Meow!\n"; } 
}; 
   
class Horse : public Pet 
{ 
public: 
    void speak() const { std::cout << "Whinny!\n"; } 
}; 
   
class Pig : public Pet 
{ 
public: 
    void speak() const { std::cout << "Oink!\n"; } 
}; 
 
int main() 
{ 
    Pet* array[5]; 
    Pet* ptr; 
    int choice, i; 
    for (i = 0; i < 5; i++) 
    { 
           std::cout << "(1) dog (2) cat (3) horse (4) pig: "; 
           std::cin >> choice; 
           switch (choice) 
           { 
           case 1:  
                ptr = new Dog; 
                break; 
           case 2:  
                ptr = new Cat; 
                break; 
           case 3:  
                ptr = new Horse; 
                break; 
           case 4:  
                ptr = new Pig; 
                break; 
           default:  
                ptr = new Pet; 
                break; 
           } 
           array[i] = ptr; 
    } 
    for (i=0; i < 5; i++) 
    { 
           array[i]->speak(); 
    } 
    return 0; 
}

Result


Related Tutorials