In this blog we are going to learn about double dispatch technique in c++. So what is double dispatch? To understand this double dispatch technique we let us re-learn polymorphism in c++.

Let us take a very simple example of run time polymorphism.

#include<iostream>
#include<memory>

class IceCream
{
    public:
      virtual void make_icecream() = 0;
};

class IceCreamWithNuts : public IceCream
{
    public:
      void make_icecream()
      {
      std::cout <<"IceCreaWithNuts\n";
      }
};

class IceCreamWithFruits : public IceCream
{
    public:
      void make_icecream()
      {
          std::cout <<"IceCreaWithFruits\n";
      } 
};


int main()
{
    std::unique_ptr<IceCream> obj_1(new IceCreamWithNuts);
    std::unique_ptr<IceCream> obj_2(new IceCreamWithFruits);

    obj_1->make_icecream();
    obj_2->make_icecream();

    return 0;
}

#g++ -std=c++11 sample.cpp -o sample

#./sample

IceCreaWithNuts
IceCreaWithFruits

Look at the main() function

int main()
{
    std::unique_ptr<IceCream> obj_1(new IceCreamWithNuts);
    std::unique_ptr<IceCream> obj_2(new IceCreamWithFruits);

    obj_1->make_icecream();
    obj_2->make_icecream();

    return 0;
}

The pointer obj_1 and the pointer obj_2 , both are pointing to IceCream . Both pointers call abstract method make_icecream(). At run time the make_function() dispatch to the function which is implemented in derived class. The decision to select right override function is based on single object.  This is called single dispatch.

Now let us discuss about multiple dispatch. As in above example the decision to select right override function on run time is based on single object. Multiple dispatch means selection of right override function based on multiple objects.

Understanding double dispatch in c++

 



Related Contents to follow