Wednesday 24 June 2020

Polymorphism

Polymorphism

Polymorphism meaning having many forms.
In C++ there are two types of polymorphism
  • Compile-time polymorphism
  • Run-Time polymorphism


Compile time polymorphism 

The binding happens at compile time, meaning based on the arguments the compiler tries to interpret the function call.
It can be observed with function overloading. Based on the type of arguments passed, the compiler decides which function to call. 

Run time polymorphism 

The binding happens at run time. Function over-riding is an example of Run-time polymorphism.
Here is a simple example of Run-time polymorphism.

In the above example, based on the type of the object the pointer is holding we would want the function to be called. If it is Dog pointer, then the Dog class's sound method is executed. This feature of the compiler to identify the type of object at run time and call the correct method is called Run time polymorphism. For this to occur the base class should have atleast one virtual function.


No comments:

Post a Comment