BIT153 ยท 0 ยท 5 marks
How late binding differs from early binding? How can you achieve dynamic polymorphism? Explain with example.
How late binding differs from early binding? How can you achieve dynamic polymorphism? Explain with example. [5]
Quick answer
Early binding means the compiler resolves the function call at compile time. The decision of which function to call is made before the program runs.
Late Binding vs Early Binding and Dynamic Polymorphism
Early Binding (Static Binding)
- Also called compile-time binding or static polymorphism
- Examples: function overloading, operator overloading
- Faster execution since binding is done at compile time
Late Binding (Dynamic Binding)
Late binding means the function call is resolved at run time, not at compile time. The decision of which function to execute depends on the actual object type during execution.
- Also called run-time binding or dynamic polymorphism
- Achieved using virtual functions and pointers/references to base class
- Slightly slower due to run-time overhead (vtable lookup)
Key Differences
| Feature | Early Binding | Late Binding |
|---|---|---|
| Resolution time | Compile time | Run time |
| Mechanism | Overloading | Virtual functions |
| Flexibility | Less flexible | More flexible |
| Speed | Faster | Slightly slower |
| Polymorphism type | Static | Dynamic |
Dynamic Polymorphism
Dynamic polymorphism is achieved in C++ by:
- Declaring a function as
virtualin the base class - Overriding that function in derived classes
- Using a base class pointer or reference to call the function
Example
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() { // virtual function -> late binding
cout << "Drawing Shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() { // overrides base class function
cout << "Drawing Circle" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() { // overrides base class function
cout << "Drawing Rectangle" << endl;
}
};
int main() {
Shape *ptr; // base class pointer
Circle c;
Rectangle r;
ptr = &c;
ptr->draw(); // calls Circle::draw() at run time
ptr = &r;
ptr->draw(); // calls Rectangle::draw() at run time
return 0;
}
Output
Drawing Circle
Drawing Rectangle
Explanation
- Without
virtual, both calls would print"Drawing Shape"(early binding). - With
virtual, the correct overridden function is called based on the actual object pointed to at run time (late binding). - This is dynamic polymorphism: the same pointer
ptrbehaves differently depending on the object it points to.
Note: The
virtualkeyword instructs the compiler to use a vtable (virtual table) mechanism to resolve function calls at run time.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.