๐ What is Early Binding?
Early Binding, also known as Static Binding or Compile-Time Binding, refers to the process where the function call is resolved at compile time.
In simpler terms, the compiler knows in advance which function to call โ before the program runs.
๐ง Real-Life Analogy
Think of a TV remote where each button is pre-assigned to a specific channel. When you press “1”, you always go to Channel 1. The connection is fixed before use, just like early binding.
๐ง Characteristics of Early Binding:
- Function call is resolved at compile time.
- Uses normal functions and function overloading.
- Does not support polymorphism.
- Faster execution (since no decision is made at runtime).
- Default behavior for non-virtual functions.
โ๏ธ Example of Early Binding
#include <iostream>
using namespace std;
class Animal {
public:
void speak() { // Non-virtual function = Early Binding
cout << "Animal speaks." << endl;
}
};
class Dog : public Animal {
public:
void speak() {
cout << "Dog barks." << endl;
}
};
int main() {
Animal a;
Dog d;
Animal* ptr;
ptr = &a;
ptr->speak(); // Output: Animal speaks (early binding)
ptr = &d;
ptr->speak(); // Output: Animal speaks (early binding again, not Dog)
return 0;
}
โ Why does the second call print “Animal speaks”?
Because speak()
is a non-virtual function โ so C++ uses early binding and resolves the function at compile time, based on the pointer type (Animal*
), not the actual object.
โ When is Early Binding Used?
- With non-virtual functions
- With function overloading
- In operator overloading
- In compile-time polymorphism
๐งพ Advantages of Early Binding
- Faster execution (function call resolved at compile time)
- Simple and easy to implement
- Useful when behavior is not expected to change at runtime
โ Disadvantages
- Lacks flexibility
- Cannot achieve runtime polymorphism
- Cannot override behavior based on object type at runtime
๐ Early Binding vs Late Binding
Feature | Early Binding | Late Binding (Runtime) |
---|---|---|
Also called | Static Binding | Dynamic Binding |
When resolved | At compile time | At runtime |
Uses | Non-virtual functions | Virtual functions |
Performance | Faster | Slightly slower |
Flexibility | Less flexible | More flexible (supports polymorphism) |
โ Summary:
- Early Binding is used when C++ can determine at compile time which function to call.
- It is default behavior for non-virtual functions.
- Common in function overloading and operator overloading.
- If you need polymorphism, use Late Binding with
virtual
functions.