• Polymorphism means multiple forms that means having more than one function with the same name but with different functionalities.
  • In C++ program there are 2 types of polymorphism, they are:
    • Compile-time polymorphism
    • Run-time polymorphism

Compile-time polymorphism

  • At compile time which is implemented known as Compile-time polymorphism. It is otherwise known as static polymorphism.
  • Method overloading is also an example for compile-time polymorphism.
  • Method overloading which allows you to have more than one function with the same function name but with different functionality.

Sample Code

using namespace std;  

class Multiply  

{  

   public:  

   int mul(int a,int b)  

   {  

       return(a*b);  

   }  

   int mul(int a,int b,int c)  

   {  

       return(a*b*c);  

  }  

 };  

int main()  

{  

    Multiply multi;  

    int res1,res2;  

    res1=multi.mul(2,3);  

    res2=multi.mul(2,3,4);  

    cout<<"\n";  

    cout<<res1;  

    cout<<"\n";  

    cout<<res2;  

    return 0;  

}  

Output

Run-time polymorphism

  • Run-time polymorphism is otherwise known as dynamic polymorphism.
  • Function overriding is an example of runtime polymorphism that means when the child class contains the method which is already present in the parent class.
  • In function overriding, parent and child class both contains the same function with the different definition.
  • The call to the function is determined at runtime is known as runtime polymorphism.

Sample Code

using namespace std;  

class Base  



    public:  

    virtual void show()  

    {  

        cout<<"Wikitechy";  

     }  

};  

class Derived:public Base  

{  

    public:  

    void show()  

    {  

        cout<<"Welcome to Wikitechy";  

    }  

};  

  

int main()  

{  

    Base* b;  

    Derived d;  

    b=&d;  

    b->show();  

                return 0;  

}  

Output

Categorized in: