Explanation:
-
Dynamic dispatch means deciding which method to call at runtime based on the object type, not reference type.
-
Achieved using virtual functions in C++ and method overriding in Java.
-
Implemented internally using a V-Table (Virtual Table).
-
Each class with virtual methods has a table storing function pointers.
-
Each object has a hidden pointer (
vptr) to its class’s V-Table. -
At runtime,
vptris checked to call the correct function.
-
Copy#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak() { cout << "Animal speaks" << endl; }
};
class Dog : public Animal {
public:
void speak() override { cout << "Dog barks" << endl; }
};
int main() {
Animal* a = new Dog();
a->speak(); // "Dog barks" -> runtime decision (dynamic dispatch)
}
-
Base* ptr = new Derived();→ Classic polymorphism. -
Why not
Drawable d = new Circle();? → Abstract class cannot be instantiated, object slicing. -
Why not
Circle* d = new Circle();? → Works, but loses polymorphism. -
Why not
Circle d = new Circle();? → Wrong, becausenewgives pointer, not object.