Single Dispatch
Single dispatch is calling of virtual method – its basics of polymorphism in C++.
// By Boris Ivanov (C) 2016. #include <iostream> #include <string> using namespace std; class A{ public: virtual void work() = 0; }; class A1: public A{ virtual void work (){ cout << "A1 do work" << "\n"; } }; int main( ) { A* a = new A1(); a->work(); }
A1 do work
Double dispatch
// By Boris Ivanov (C) 2016. class Surface; class Table; class Window; class Ball; class Baloon; class Sphere{ public: virtual void hit (Surface& a) = 0; virtual void RealTimeHit (Table& a) = 0; virtual void RealTimeHit (Window& a) = 0; }; class Surface { public: virtual void hit (Sphere& b) = 0; virtual void RealTimeHit (Ball& b) = 0; virtual void RealTimeHit (Baloon& b) = 0; }; class Ball : public Sphere { void hit (Surface& s) { s.RealTimeHit(*this); } void RealTimeHit (Table& a){ cout << "Ball hit Table and bounced" << "\n"; } void RealTimeHit (Window& a){ cout << "Ball hit Window and broken it!" << "\n"; } }; class Baloon : public Sphere { void hit (Surface& s) { s.RealTimeHit(*this); } void RealTimeHit (Table& a){ cout << "Baloon hit Table and bounced" << "\n"; } void RealTimeHit (Window& a){ cout << "Baloon hit Window and bounced it!" << "\n"; } }; class Table : public Surface { void hit (Sphere& s) { s.RealTimeHit(*this); } void RealTimeHit (Ball& a){ cout << "Table hit by Ball but survived" << "\n"; } void RealTimeHit (Baloon& a){ cout << "Table hit by Baloon and baloon stuck in Jam!" << "\n"; } }; class Window : public Surface { void hit (Sphere& s) { s.RealTimeHit(*this); } void RealTimeHit (Ball& a){ cout << "Window hit by Ball. Oops!" << "\n"; } void RealTimeHit (Baloon& a){ cout << "Window hit by baloon! Nothing serious!" << "\n"; } }; int main( ) { Sphere * a1 = new Ball(); Sphere * a2 = new Baloon(); Surface * b1 = new Table(); Surface * b2 = new Window(); a1->hit(*b1); // Ball > Table a2->hit(*b2); // Baloon > Window a1->hit(*b2); // Ball > Window a2->hit(*b1); // Baloon > Table return 0; }
Result:
Table hit by Ball but survived
Window hit by baloon! Nothing serious!
Window hit by Ball. Oops!
Table hit by Baloon and baloon stuck in Jam!