CSC/ECE 517 Fall 2010/ch2 5c gn
Dynamic Dispatch
Introduction
The process of identifying which version of the function to call based on the runtime type of the reference being used to execute the function. Dynamic Dispatch generally happens in OOL. For example, we can have a super class which defines a particular function and then there is a subclass which defines the same function (called overriding). When a reference to the super class is used to execute that function, then which version of the function gets execute depends on the type, the reference points to at that time, instead of type of the reference. In literature it also given different names like Runtime Binding or Dynamic Polymorphism http://en.wikipedia.org/wiki/Dynamic_polymorphism.
To further understand what Dynamic Dispatch is, consider the below example:
class Animal { public void walk() { System.out.println("Animal::walk"); } }
class Dog extends Animal { public void walk() { System.out.println("Dog::walk"); } } class Cat extends Animal { public void walk() { System.out.println("Cat::walk"); } }
Animal a = new _______(); a.walk();
The compiler cannot decide which version of walk (Animal, Dog or Cat) during compile time. So the decision of which version of the walk function to call will be deferred till the runtime.
Why we need Dynamic Dispatch
Dynamic Dispatch is one of the inherent feature of an Object Oriented Languauge [1 http://en.wikipedia.org/wiki/Object_oriented_language].
How Dynamic Dispatch works
Dynamic Dispatch working in Detail
class Cat { public: void talk() { cout << "Meow!!"; } }; class Dog { public: void talk() { cout << "Bark!!"; } }; struct Cat { int __id__; // 0 char name[10]; }; struct Dog { int __id__; // 1 char name[10]; }; void cat_talk() { printf("meow!"); } void dog_talk() { printf("Bark!!"); } void talk(void *object) { int id = *(int *)object; vtable[id](); } void (*vtable[2]); vtable[0] = cat_talk; vtable[1] = dog_talk; Cat *c = new Cat(); Cat *c = malloc(sizeof(cat)); c->__id__ = 0;