How virtual functions implement polymorphism. - C++ Class

C++ examples for Class:Polymorphism

Description

How virtual functions implement polymorphism.

Demo Code

#include <iostream> 
   //from w  w  w.j ava2 s . c  o  m
class Pet 
{ 
public: 
    Pet():age(1) { std::cout << "Pet constructor ...\n"; } 
    ~Pet() { std::cout << "Pet destructor ...\n"; } 
    void move() const { std::cout << "Pet, move one step\n"; } 
    virtual void speak() const { std::cout << "Pet speak!\n"; } 
   
protected: 
    int age; 
}; 
   
class Dog : public Pet 
{ 
public: 
    Dog() { std::cout << "Dog constructor ...\n"; } 
    ~Dog() { std::cout << "Dog destructor ..\n"; } 
    void wagTail() { std::cout << "Wagging tail ...\n"; } 
    void speak() const { std::cout << "Woof!\n"; } 
    void move() const { std::cout << "Dog moves 5 steps ...\n"; } 
}; 
   
int main() 
{ 
    Pet *pDog = new Dog; 
    pDog->move(); 
    pDog->speak(); 
    return 0; 
}

Result


Related Tutorials