Early binding and Late binding in C++

C++Server Side ProgrammingProgramming

In this section we will see what is early binding and what is late binding in C++. The binding means the process of converting identifiers into addresses. For each variables and functions this binding is done. For functions it is matching the call with the right function definition by the compiler. The binding is done either at compile time or at runtime.

Early Binding

This is compile time polymorphism. Here it directly associates an address to the function call. For function overloading it is an example of early binding.

Example

 Live Demo

#include<iostream>
using namespace std;
class Base {
   public:
   void display() {
      cout<<" In Base class" <<endl;
   }
};
class Derived: public Base {
   public:
   void display() {
      cout<<"In Derived class" << endl;
   }
};
int main(void) {
   Base *base_pointer = new Derived;
   base_pointer->display();
   return 0;
}

Output

In Base class

Late Binding

This is run time polymorphism. In this type of binding the compiler adds code that identifies the object type at runtime then matches the call with the right function definition. This is achieved by using virtual function.

Example

 Live Demo

#include<iostream>
using namespace std;
class Base {
   public:
   virtual void display() {
      cout<<"In Base class" << endl;
   }
};
class Derived: public Base {
   public:
   void display() {
      cout<<"In Derived class" <<endl;
   }
};
int main() {
   Base *base_pointer = new Derived;
   base_pointer->display();
   return 0;
}

Output

In Derived class
raja
Published on 02-Apr-2019 13:48:19
Advertisements