Difference between Compile time and Runtime Polymorphism in C++

CompileTime vs RunTime Polymorphism

We first recommend you the go through the following posts, to understand these better. Compile Time vs Runtime Polymorphism



Now, we will talk about the major differences between two, we hope you understand the basics about the two fairly –

Runtime Polymorphism is also known as Dynamic Method Dispatch (Dynamic Polymorphism).

How Polymorphism works in C++

There are two types of polymorphism that occur in C++ which are –

  • Compile time polymorphism (demonstrates static/early binding)
    • Function Overloading
    • Operator Overloading

Now, compile time polymorphism is classic example of how the decision happens at compile time, in other words, objects, functions and classes are binded early at compile time and are staic

  • Run time polymorphism (demonstrates dynamic/late binding)
    • Function Overriding (Achieved with help of virtual keyword)

The decision to bind objects, function, classes etc together is made at run time and is dynamic i.e. happens very late at runtime.

Compile Time Polymorphism

Function Overloading

When in a class there are multiple functions with same name, however the arguments passed in the function may different in number or type then the program exhibits behavior of function overloading

  • For example
myFunction(int a, int b) and myFunction(double a, double b).

Let us have a look on a program to understand this

function overloading

Example –

#include <iostream>
using namespace std;

class PrepInsta {
  void sum(int a)
    cout << "Sum of the int type variable is:" << a << endl;
  void sum(double a) {
    cout << "sum of the double type variable is:" << a << endl;
  void sum(int a, int b) 
cout << "Sum of int type variables are:" << a + b << endl; }
void sum(double a, double b)
cout << "Sum of double type variables are:" << a + b << endl;
} }; int main() { PrepInsta obj; obj.sum(5); obj.sum(500.263); obj.sum(5,3);
obj.sum(5.333,3.167); return 0; }

Output –

Sum of the int type variable is:5                                                                                                                                                           
sum of the double type variable is:500.263
Sum of int type variables are:8
Sum of double type variables are:8.5

Now, in the above, the functions go to their correct argument type in class PrepInsta, this is called function overloading