Use the Parent pointer polymorphically to access virtual functions and dynamic_cast operator - C++ Class

C++ examples for Class:Polymorphism

Description

Use the Parent pointer polymorphically to access virtual functions and dynamic_cast operator

Demo Code

#include <iostream> 
 
class Pet //from w  w  w .  j  av  a  2 s. c  om
{ 
public: 
    Pet():age(1) { std::cout << "Pet constructor ...\n"; } 
    virtual ~Pet() { std::cout << "Pet destructor ...\n"; } 
    virtual void speak() const { std::cout << "Pet speak!\n"; } 
protected: 
    int age; 
}; 
 
class Cat: public Pet 
{ 
public: 
    Cat() { std::cout << "Cat constructor ...\n"; } 
    ~Cat() { std::cout << "Cat destructor ...\n"; } 
    void speak() const { std::cout << "Meow!\n"; } 
    void purr() const { std::cout << "Rrrrrrrrrrr!\n"; } 
}; 
 
class Dog: public Pet 
{ 
public: 
    Dog() { std::cout << "Dog constructor ...\n"; } 
    ~Dog() { std::cout << "Dog destructor ...\n"; } 
    void speak() const { std::cout << "Woof!\n"; } 
}; 
 
int main() 
{ 
    const int numberPets = 3; 
    Pet* zoo[numberPets]; 
    Pet* pPet; 
    int choice, i; 
    for (i = 0; i < numberPets; i++) 
    { 
            std::cout << "(1) Dog (2) Cat: "; 
            std::cin >> choice; 
            if (choice == 1) 
                 pPet = new Dog; 
            else 
                 pPet = new Cat; 
 
            zoo[i] = pPet; 
    } 
 
    std::cout << "\n"; 
 
    for (i = 0; i < numberPets; i++) 
    { 
            zoo[i]->speak(); 
 
            Cat *pRealCat =  dynamic_cast<Cat *> (zoo[i]); 
 
            if (pRealCat) 
                 pRealCat->purr(); 
            else 
                  std::cout << "Uh oh, not a cat!\n"; 
 
            delete zoo[i]; 
            std::cout << "\n"; 
    } 
 
    return 0; 
}

Result


Related Tutorials