What are the different types of polymorphism in C++?

Polymorphism: Polymorphism means multiple forms. It means having more than one function with the same function name but with different functionalities.

Polymorphism is of two types:

C++ Interview Questions
  • Runtime polymorphism

Runtime polymorphism is also known as dynamic polymorphism. Function overriding is an example of runtime polymorphism. Function overriding means when the child class contains the method which is already present in the parent class. Hence, the child class overrides the method of the parent class. In case of 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.

Let’s understand this through an example:

  1. #include <iostream>  
  2. using namespace std;  
  3. class Base  
  4. {  
  5.     public:  
  6.     virtual void show()  
  7.     {  
  8.         cout<<“javaTpoint”;  
  9.      }  
  10. };  
  11. class Derived:public Base  
  12. {  
  13.     public:  
  14.     void show()  
  15.     {  
  16.         cout<<“javaTpoint tutorial”;  
  17.     }  
  18. };  
  19.   
  20. int main()  
  21. {  
  22.     Base* b;  
  23.     Derived d;  
  24.     b=&d;  
  25.     b->show();  
  26.                 return 0;  
  27. }  

Output:

javaTpoint tutorial
  • Compile time polymorphism

Compile-time polymorphism is also known as static polymorphism. The polymorphism which is implemented at the compile time is known as compile-time polymorphism. Method overloading is an example of compile-time polymorphism.

Method overloading: Method overloading is a technique which allows you to have more than one function with the same function name but with different functionality.

Method overloading can be possible on the following basis:

  • The return type of the overloaded function.
  • The type of the parameters passed to the function.
  • The number of parameters passed to the function.

Let’s understand this through an example:

  1. #include <iostream>  
  2. using namespace std;  
  3. class Multiply  
  4. {  
  5.    public:  
  6.    int mul(int a,int b)  
  7.    {  
  8.        return(a*b);  
  9.    }  
  10.    int mul(int a,int b,int c)  
  11.    {  
  12.        return(a*b*c);  
  13.   }  
  14.  };  
  15. int main()  
  16. {  
  17.     Multiply multi;  
  18.     int res1,res2;  
  19.     res1=multi.mul(2,3);  
  20.     res2=multi.mul(2,3,4);  
  21.     cout<<“\n”;  
  22.     cout<<res1;  
  23.     cout<<“\n”;  
  24.     cout<<res2;  
  25.     return 0;  
  26. }  

Output:

6
24
  • In the above example, mul() is an overloaded function with the different number of parameters.