static and dynamic binding in c++ details:

Binding means connection between a function call and the actual code execution when we call the defined function. when a function call gets resolved at the time of compilation it is called “static binding” and when a function call get resolved at run time it is called dynamic binding. the static binding is also called early binding and dynamic binding as late binding.

Static binding example with explanation:

#include<iostream>
int add(int a,int b)
{
        return ( a + b);
}

int main()

{
             int a  = add();  // direct function call line num 8
             return 0;
}

In above example add(int, int) is a direct function call at line number 8. when compiler see this call at line 8 it will  replace the add(int a, int b) function call with the machine instruction that tells the CPU to jump to the address of the add(int a, int b) function.

Dynamic binding details:

In c++  dynamic binding can be achieved by using virtual function.

#include<iostream>
using namespace std;

class A {
     public:
     A(){};
     virtual void hello(){
     };
};

class B:public A {

public:
    void hello()
    {
       cout<<"Hello from derived class B"<<endl;
    }
};
class C:public A{
     public:
     void hello()
     {
        cout<<"Hello from derived class C"<<endl;
     }
};

int main()
{
     A *base_pointer = new B();
     base_pointer->hello();
     A *base_pointer_a = new C();
     base_pointer_a->hello();
}

Here when we call function hello() by A *base_pointer = new B();
base_pointer->hello(); The function call will be resolved at run time. this is called dynamic binding. Here we are calling derived class function by base class pointer at run time using virtual function.



Related Contents to follow