09 September 2011

Dynamic Binding (Dispatch) by example

SA,
Dynamic Dispatch is the process of mapping a message to a specific sequence of code (method) at runtime. This is done to support the cases where the appropriate method cannot be determined at compile-time (i.e. statically)
The above paragraph is from Wikipedia It illustrate what is dynamic binding. It is simply that, We have a method that being called/send on some object, the actual implementation of the method to chosen is based on the runtime type of that object. It is used in Polymorphism. it can be illustrated by this example:
Class A
{
      someFunc();
}

Class B extends A
{
     someFunc();

}

A aInstance = new B();
aInstance.someFunc();
in this case, and if the language supports dynamic binding (such as Java/Ojbc).. the implementation of the subclass who will be invoked. But in C++ (I think in C# also), the dynamic dispatch is optional and non-default. so to enable it, you mark the method with the virtual keyword. From wikipedia:
Although the overhead involved in this dispatch mechanism is low, it may still be significant for some application areas that the language was designed to target. For this reason, Bjarne Stroustrup, the designer of C++, elected to make dynamic dispatch optional and non-default. Only functions declared with the virtual keyword will be dispatched based on the runtime type of the object; other functions will be dispatched based on the object's static type.
See this example in C++:
#include <iostream>

using namespace std;

class Super
{
public:
    void someFunction()
    {
        cout << " In Super function" << endl;
    }
};

class Sub : public Super
{
public:
    void someFunction()
    {
        cout << " In Sub function" << endl;
    }
};

int main(void)
{
    Super* s = new Sub;

    s->someFunction();
    
    delete s;
    
    return 0;
}
The Super class method will be invoked, but if you added the virtual keyword at the start of the super class someFuncation() to be: virtual void someFunction() The dynamic binding will be enable and the subclass's method will be invoked instead.

No comments: