๐ What is Late Binding?
Late Binding, also known as Dynamic Binding or Runtime Binding, refers to the process where the function call is resolved at runtime.
In C++, late binding is achieved using virtual functions. This is the foundation of runtime polymorphism.
๐ง Real-Life Analogy
Think of a remote control with programmable buttons. You can change which channel the button connects to even while watching. That’s dynamic behavior โ just like late binding.
๐ง Characteristics of Late Binding:
- Function call is resolved at runtime, not compile time.
- Requires virtual functions in the base class.
- Supports polymorphism (runtime flexibility).
- Slower than early binding (because of runtime decision-making).
โ๏ธ Syntax of Virtual Function:
class Base {
public:
virtual void display(); // 'virtual' enables late binding
};
๐งช Example: Late Binding Using Virtual Function
#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak() { // Virtual function
cout << "Animal speaks." << endl;
}
};
class Dog : public Animal {
public:
void speak() override {
cout << "Dog barks." << endl;
}
};
int main() {
Animal* ptr;
Dog d;
ptr = &d;
ptr->speak(); // Output: Dog barks (Late Binding)
return 0;
}
โ Explanation:
- The base class function
speak()
is marked virtual. - At runtime, C++ checks the actual object (
Dog
) and callsDog::speak()
. - This is late binding, allowing the correct function to be chosen dynamically.
โ When to Use Late Binding:
- When you want to override base class functions in derived classes.
- When the object type is not known until runtime.
- For building flexible and reusable code (e.g., GUI tools, games, frameworks).
๐ Advantages of Late Binding:
- Supports runtime polymorphism.
- Allows extensibility in large projects.
- Enables code generalization using base class pointers or references.
โ Disadvantages:
- Slightly slower than early binding (due to virtual table lookup).
- Adds a small runtime overhead.
- Can be misused if not structured properly.
๐ Comparison: Early Binding vs Late Binding
Feature | Early Binding | Late Binding |
---|---|---|
Also known as | Static Binding | Dynamic Binding |
Time of resolution | Compile time | Runtime |
Keyword used | None (default) | virtual |
Flexibility | Less flexible | More flexible (polymorphic) |
Performance | Faster | Slightly slower |
Example use case | Function overloading | Virtual function overriding |
๐ฏ Summary:
- Late Binding in C++ allows calling derived class functions using base class pointers at runtime.
- Achieved using the
virtual
keyword. - It’s essential for implementing runtime polymorphism.
- Offers flexibility and extensibility in object-oriented programming.