BIT153 ยท 2078 ยท 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 lookup (via vtable), but provides flexibility
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() override { // overriding in derived class
cout << "Drawing Circle" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() override { // overriding in derived class
cout << "Drawing Rectangle" << endl;
}
};
int main() {
Shape *ptr; // base class pointer
Circle c;
Rectangle r;
ptr = &c;
ptr->draw(); // Output: Drawing Circle (resolved at run time)
ptr = &r;
ptr->draw(); // Output: Drawing Rectangle (resolved at run time)
return 0;
}
Output
Drawing Circle
Drawing Rectangle
Explanation
ptris a pointer of typeShape*- At compile time, the compiler cannot determine which
draw()to call - At run time, the actual object (
CircleorRectangle) determines which version ofdraw()executes - This is late binding in action, enabling dynamic polymorphism
Note: Without the
virtualkeyword, early binding would occur andShape::draw()would always be called regardless of the actual object type.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.