
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Early Binding and Late Binding in C++
In C++, binding is the process of connecting names such as variables and functions to their actual memory locations.
When you intend to call a function, the program must identify the proper function definition for the execution. So, binding is the process of making this connection. This happens either at compile time (early binding) or at runtime (late binding).
Early Binding
This is compile time polymorphism and decides which function to call before it runs, making execution faster and direct.
Example
In this example, we demonstrate the early binding, where the base class function runs instead of the derived class function due to the missing 'virtual' keyword.
#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
Following is the output to the above program:
In Base class
Late Binding
The Late Binding is the 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
In this example, we demonstrate runtime polymorphism using a base class pointer to call an overridden function in a derived class, ensuring the correct function executes based on the actual object type.
#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
Following is the output to the above program:
In Derived class