Late binding and Dynamic binding (C++)

What is Late binding?

  • Late binding is also k/a Runtime polymorphism.

  • Late binding can be achieved by using a virtual function.

Virtual function: -

A virtual Function is a base class member function that is redefined in derived classes to achieve polymorphism. A virtual function in C++ helps ensure you call the correct function via a reference or pointer.

Code: -

#include <iostream>

using namespace std;

class Base{

public:

virtual void Output(){

cout << "Output Base class" << endl;

}

void Display(){

cout << "Display Base class" << endl;

}

};

class Derived : public Base{

public:

void Output(){

cout << "Output Derived class" << endl;

}

void Display()

{

cout << "Display Derived class" << endl;

}

};

int main(){

Base* bpointr;

Derived dpointr;

bpointr = &dpointr;// pointing base class pointer to the derived class object

bpointr->Output();//This function calls the member function of the derived class because we used the virtual keyword in the base class

bpointr->Display();// This function calls a function of the base class itself because we didn't use virtual keyword with it

}

Output:

Basically what we got to understand from this code is we use the virtual keyword when we have to show virtual version of the derived class.

What is early Binding?

  • Also k/a compile-time polymorphism.

  • By default, early binding happens in C++.

  • Can be achieved by using operator overloading and function overloading.

Function overloading:-

Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters.

Code:-

add(int a, int b) add(double a, double b)

//These functions will give different outputs based on the arguments we give them.

Operator overloading:-

We use operator overloading when we have to perform different operations on user-defined data type (class) these operations can not be performed otherwise.

The difference in Runtime and Compile-time polymorphism:-

Runtime polymorphismCompile-time polymorphism
Slow execution.Fast execution.
All information needs to call a function come to know at run time.All information needed to call a function is known at compile time.
Flexibility.Efficiency.