C++ Polymorphism

C++ Polymorphism

The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a greek word. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation and polymorphism.

There are two types of polymorphism in C++:

1) Compile time polymorphism: It is achieved by function overloading and operator overloading which is also known as static binding or early binding.
2) Runtime polymorphism: It is achieved by method overriding which is also known as dynamic binding or late binding.

Runtime Polymorphism Example

Let's see a simple example of runtime polymorphism in C++.

    #include <iostream>  
    using namespace std;  
    class Animal {  
        public:  
    void eat(){    
    cout<<"Eating...";    
        }      
    };   
    class Dog: public Animal    
    {    
     public:  
     void eat()    
        {    
           cout<<"Eating bread...";    
        }    
    };  
    int main(void) {  
       Dog d = Dog();    
       d.eat();  
       return 0;  
    }  

Output:

Eating bread..

Runtime Polymorphism Example: By using two derived class

Let's see another example of runtime polymorphism in C++ where we are having two derived classes.

    #include <iostream>  
    using namespace std;  
    class Shape {  
        public:  
    virtual void draw(){    
    cout<<"drawing..."<<endl;    
        }      
    };   
    class Rectangle: public Shape    
    {    
     public:  
     void draw()    
        {    
           cout<<"drawing rectangle..."<<endl;    
        }    
    };  
    class Circle: public Shape    
    {    
     public:  
     void draw()    
        {    
           cout<<"drawing circle..."<<endl;    
        }    
    };  
    int main(void) {  
        Shape *s;  
        Shape sh;  
            Rectangle rec;  
            Circle cir;  
            s=&sh;  
         s->draw();   
            s=&rec;  
         s->draw();    
        s=○  
         s->draw();   
    }  

Output:

drawing...
drawing rectangle...
drawing circle...

Runtime Polymorphism with Data Members

Runtime Polymorphism can be achieved by data members in C++. Let's see an example where we are accessing the field by reference variable which refers to the instance of derived class.

    #include <iostream>  
    using namespace std;  
    class Animal {  
        public:  
        string color = "Black";    
    };   
    class Dog: public Animal   
    {    
     public:  
        string color = "Grey";    
    };  
    int main(void) {  
         Animal d= Dog();    
        cout<<d.color;   
    }  

Output:

Black