Skip to content

Late Binding

๐Ÿ“˜ 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 calls Dog::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

FeatureEarly BindingLate Binding
Also known asStatic BindingDynamic Binding
Time of resolutionCompile timeRuntime
Keyword usedNone (default)virtual
FlexibilityLess flexibleMore flexible (polymorphic)
PerformanceFasterSlightly slower
Example use caseFunction overloadingVirtual 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.