{"id":6486,"date":"2022-11-27T14:49:55","date_gmt":"2022-11-27T14:49:55","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/the-visitor-pattern\/"},"modified":"2023-08-10T19:17:27","modified_gmt":"2023-08-10T19:17:27","slug":"the-visitor-pattern","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/the-visitor-pattern\/","title":{"rendered":"The Visitor Pattern"},"content":{"rendered":"<p>The <a href=\"https:\/\/en.wikipedia.org\/wiki\/Visitor_pattern\">Visitor Pattern<\/a> encapsulates an operation executed on an object hierarchy as an object and enables it to define new operations without changing the object hierarchy.<\/p>\n<p><!--more--><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6479\" style=\"display: block; margin-left: auto; margin-right: auto;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern.png\" alt=\"BehavioralPattern\" width=\"650\" height=\"329\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern.png 1234w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern-300x152.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern-1024x518.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern-768x388.png 768w\" sizes=\"auto, (max-width: 650px) 100vw, 650px\" \/><\/p>\n<p>The Visitor Pattern from the book \u00a0 &#8220;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Design_Patterns\">Design Patterns: Elements of Reusable Object-Oriented Software&#8221;<\/a> is legendary for two reasons. First, for its complicatedness, and second, for a technique called double dispatch. Double dispatch describes the process of choosing the member function based on the object and the function arguments. Of course, the complicatedness of the Visitor Pattern is mainly due to the fact that double dispatch is not natively supported in C++, such as in <a href=\"https:\/\/en.wikipedia.org\/wiki\/Eiffel_(programming_language)\">Eiffel<\/a>.<\/p>\n<p>Let me first write about the Visitor Pattern before I discuss single dispatch and double dispatch.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Visitor_Pattern\"><\/span>Visitor Pattern<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Purpose\"><\/span>Purpose<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li>Encapsulates an operation executed on an object hierarchy in an object<\/li>\n<li>Enables to define new operations without changing the object hierarchy<\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"Use_Case\"><\/span>Use Case<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li>Operations should be performed on an object hierarchy<\/li>\n<li>The operations change frequently<\/li>\n<li>The object hierarchy is stable<\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"Structure\"><\/span>Structure<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><code><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6482\" style=\"display: block; margin-left: auto; margin-right: auto;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/VisitorUML.png\" alt=\"Visitor\" width=\"400\" height=\"275\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/VisitorUML.png 400w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/VisitorUML-300x206.png 300w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/code><\/p>\n<p><strong><code>Visitor<\/code><\/strong><\/p>\n<ul>\n<li>Defines the <code>visit<\/code> operation on the object structure<\/li>\n<\/ul>\n<p><strong><code>ConcreteVistor<\/code><\/strong><\/p>\n<ul>\n<li>Implements the <code>visit<\/code> operation<br \/>\n<strong><code><\/code><\/strong><\/li>\n<\/ul>\n<p><strong><code>Element<\/code><\/strong><\/p>\n<ul>\n<li>Defines the <code>accept<\/code> operation that takes a visitor as an argument<br \/>\n<strong><code><\/code><\/strong><\/li>\n<\/ul>\n<p><strong><code>ConcreteElement<\/code><\/strong><\/p>\n<ul>\n<li>Implements the <code>accept<\/code> operation<\/li>\n<\/ul>\n<p>I assume this graphic was too simple. The following picture from the<a href=\"https:\/\/en.wikipedia.org\/wiki\/Visitor_pattern\"> Visitor Pattern<\/a> on Wikipedia provides more insight.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6483\" style=\"display: block; margin-left: auto; margin-right: auto;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/VisitorWiki.png\" alt=\"VisitorWiki\" width=\"700\" height=\"315\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/VisitorWiki.png 959w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/VisitorWiki-300x135.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/VisitorWiki-768x345.png 768w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/><\/p>\n<p>By Fuhrmanator &#8211; Using the PlantUML software <a href=\"https:\/\/bit.ly\/3MDbtCK\">https:\/\/bit.ly\/3MDbtCK<\/a>, CC BY-SA 3.0, <a href=\"https:\/\/commons.wikimedia.org\/w\/index.php?curid=122709059\">https:\/\/commons.wikimedia.org\/w\/index.php?curid=122709059<\/a><\/p>\n<p>This picture gives a very good impression of the Visitor Pattern. Let me use it to explain the structure and the dynamic behavior of the Visitor Pattern.<\/p>\n<ul>\n<li>Structure<\/li>\n<\/ul>\n<p>The Visitor Pattern has two type of hierarchies. The object hierarchy (<code>CarElement<\/code>) and the operation hierarchy (<code>CarElementVisitor<\/code>). The object hierarchy is pretty stable, but the operation hierarchy may support new operations. Both classes, <code>CarElement<\/code> and <code>CarElementVisitor<\/code> act as interfaces. This means that each concrete car element <code>Wheel<\/code>, <code>Engine<\/code>, <code>Body<\/code>, and <code>Car<\/code> must implement the <code>accept(CarElementVisitor)<\/code> member function. Accordingly, each concrete operation <code>CarElementDoVisitor<\/code> and <code>CarElementPrintVisitor<\/code> must implement the four overloads <code>visit(Wheel)<\/code>, <code>visit(Engine)<\/code>, <code>visit(Body)<\/code>, and <code>visit(Car)<\/code>.<\/p>\n<ul>\n<li>Dynamic Behavior<\/li>\n<\/ul>\n<p>Let&#8217;s assume that the operation <code>CarElementPrintVisitor<\/code> is applied to the object hierarchy. The job of <code>CarElementPrintVisitor<\/code> may be to print the name of the visited car part. First, a car element such as <code>Engine<\/code> accepts the visitor (<code>accept(CarElementVisitor)<\/code>) and uses the visitor to call back into the operations hierarchy (<code>visitor.visit(this)<\/code>) using itself as an argument. This ensures that the <code>visit(Engine)<\/code> overload on the <code>CarElementPrintVisitor<\/code> is called. Visiting the <code>Car<\/code> is special. A <code>Car<\/code> consists of various car elements. Consequently, <code>Car<\/code>&#8216;s accept member function delegates the accept call to all its car parts.<\/p>\n<p>Here is the crucial observation about the Visitor.<strong> It depends on two objects, which operation is performed: the visitor and the visited object.<\/strong><\/p>\n<h3><span class=\"ez-toc-section\" id=\"Example\"><\/span>Example<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The following example literally translated the previous picture into code.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ visitor.cpp<\/span>\n\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\n<span style=\"color: #009999;\">#include &lt;string&gt;<\/span>\n<span style=\"color: #009999;\">#include &lt;vector&gt;<\/span>\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">CarElementVisitor<\/span>;\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">CarElement<\/span> {                                    <em><span style=\"color: #0099ff;\"> \/\/ (5)  <\/span> <\/em>    \n <span style=\"color: #9999ff;\">public:<\/span>\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> accept(CarElementVisitor<span style=\"color: #555555;\">&amp;<\/span> visitor) <span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;\n    <span style=\"color: #006699;\">virtual<\/span> ~CarElement() = default;\n};\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Body<\/span>;\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Car<\/span>;\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Engine<\/span>;\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Wheel<\/span>;\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">CarElementVisitor<\/span> {                             <em><span style=\"color: #0099ff;\"> \/\/ (6)<\/span><\/em> \n <span style=\"color: #9999ff;\">public:<\/span>\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Body body) <span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Car car) <span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Engine engine) <span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Wheel wheel) <span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;\n    <span style=\"color: #006699;\">virtual<\/span> ~CarElementVisitor() = default;\n};\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Wheel<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> CarElement {\n <span style=\"color: #9999ff;\">public:<\/span>\n    Wheel(<span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> n)<span style=\"color: #555555;\">:<\/span> name(n) { }\n\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> accept(CarElementVisitor<span style=\"color: #555555;\">&amp;<\/span> visitor) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        visitor.visit(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>);\n    }\n\n    std<span style=\"color: #555555;\">::<\/span>string getName() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> name;\n    }\n <span style=\"color: #9999ff;\">private:<\/span>\n    std<span style=\"color: #555555;\">::<\/span>string name;\n};\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Body<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> CarElement {\n <span style=\"color: #9999ff;\">public:<\/span>\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> accept(CarElementVisitor<span style=\"color: #555555;\">&amp;<\/span> visitor) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        visitor.visit(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>);\n    }\n};\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Engine<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> CarElement {\n <span style=\"color: #9999ff;\">public:<\/span>\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> accept(CarElementVisitor<span style=\"color: #555555;\">&amp;<\/span> visitor) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        visitor.visit(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>);\n    }\n};\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Car<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> CarElement {\n <span style=\"color: #9999ff;\">public:<\/span>\n    Car(std<span style=\"color: #555555;\">::<\/span>initializer_list<span style=\"color: #555555;\">&lt;<\/span>CarElement<span style=\"color: #555555;\">*&gt;<\/span> carElements )<span style=\"color: #555555;\">:<\/span> elements{carElements} {}\n   \n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> accept(CarElementVisitor<span style=\"color: #555555;\">&amp;<\/span> visitor) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        <span style=\"color: #006699; font-weight: bold;\">for<\/span> (<span style=\"color: #006699; font-weight: bold;\">auto<\/span> elem <span style=\"color: #555555;\">:<\/span> elements) {\n            elem<span style=\"color: #555555;\">-&gt;<\/span>accept(visitor);\n        }\n        visitor.visit(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>);\n    }\n <span style=\"color: #9999ff;\">private:<\/span>\n    std<span style=\"color: #555555;\">::<\/span>vector<span style=\"color: #555555;\">&lt;<\/span>CarElement<span style=\"color: #555555;\">*&gt;<\/span> elements;                  <em><span style=\"color: #0099ff;\"> \/\/ (7)<\/span> <\/em>\n};\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">CarElementDoVisitor<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> CarElementVisitor {\n   \n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Body body) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Moving my body\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n    }\n\n     <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Car car) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Starting my car\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n    }\n\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Wheel wheel) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Kicking my \"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> wheel.getName() <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\" wheel\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n    }\n\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Engine engine) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Starting my engine\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n    }\n};\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">CarElementPrintVisitor<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> CarElementVisitor {\n   \n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Body body) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Visiting body\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n    }\n\n     <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Car car) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Visiting car\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n    }\n\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Wheel wheel) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Visiting \"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> wheel.getName() <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\" wheel\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n    }\n\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> visit(Engine engine) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Visiting engine\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n    }\n};\n\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>() {\n\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n\n    Wheel wheelFrontLeft(<span style=\"color: #cc3300;\">\"front left\"<\/span>);        \n    Wheel wheelFrontRight(<span style=\"color: #cc3300;\">\"front right\"<\/span>);\n    Wheel wheelBackLeft(<span style=\"color: #cc3300;\">\"back left\"<\/span>);\n    Wheel wheelBackRight(<span style=\"color: #cc3300;\">\"back right\"<\/span>);\n    Body body;\n    Engine engine;\n    Car car {<span style=\"color: #555555;\">&amp;<\/span>wheelFrontLeft, <span style=\"color: #555555;\">&amp;<\/span>wheelFrontRight, <span style=\"color: #555555;\">&amp;<\/span>wheelBackLeft, <span style=\"color: #555555;\">&amp;<\/span>wheelBackRight,\n             <span style=\"color: #555555;\">&amp;<\/span>body, <span style=\"color: #555555;\">&amp;<\/span>engine};\n\n    CarElementPrintVisitor carElementPrintVisitor; \n\n    engine.accept(carElementPrintVisitor);       <em><span style=\"color: #0099ff;\">\/\/ (1) <\/span><\/em>             \n    car.accept(carElementPrintVisitor);         <span style=\"color: #0099ff;\"><em> \/\/ (2)<\/em>  <\/span>        \n\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n\n    CarElementDoVisitor carElementDoVisitor;\n\n    engine.accept(carElementDoVisitor);          <em><span style=\"color: #0099ff;\">\/\/ (3)<\/span><\/em>             \n    car.accept(carElementDoVisitor);            <span style=\"color: #0099ff;\"><em> \/\/ (4)  <\/em>   <\/span>   \n\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n\n}\n<\/pre>\n<\/div>\n<p>At the beginning of the <code>main<\/code> function, all parts of the car are created. Afterward, the engine and the car accept the <code>carElementPrintVisitor<\/code> (lines 1 and 2). In lines (3) and (4), both objects are accepted by the <code>carElementDoVisitor<\/code>. <code>CarElement<\/code> (line 5) and <code>CarElementVisitor<\/code> (line 5) are the abstract base classes of the object hierarchy and the operation hierarchy. According to the picture, the concrete car elements and visitors are created. The car is the most interesting car element because it holds its car elements in a<code> std::vector&lt;Element*&gt; <\/code>(line 7).<\/p>\n<p>Finally, here is the output of the program:<\/p>\n<h3><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6484\" style=\"display: block; margin-left: auto; margin-right: auto;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/visitor.png\" alt=\"visitor\" width=\"300\" height=\"439\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/visitor.png 367w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/visitor-205x300.png 205w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/h3>\n<h3><span class=\"ez-toc-section\" id=\"Related_Patterns\"><\/span>Related Patterns<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The Visitor Pattern is probably the design pattern of the book &#8220;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Design_Patterns\">Design Patterns: Elements of Reusable Object-Oriented Software&#8221;<\/a> which has the highest pattern density.<\/p>\n<ul>\n<li>The stable object hierarchy typically applies the <a href=\"https:\/\/www.modernescpp.com\/index.php\/the-composite-pattern\">Composite Pattern<\/a>.<\/li>\n<li>The <a href=\"https:\/\/en.wikipedia.org\/wiki\/Iterator_pattern\">Iterator Pattern<\/a> is often used to iterate through the object hierarchy.<\/li>\n<li>New elements can be created with a creational pattern, such as <a href=\"https:\/\/www.modernescpp.com\/index.php\/factory-method\">Factory Method<\/a> or\u00a0 <a href=\"https:\/\/en.wikipedia.org\/wiki\/Prototype_pattern\">Prototype<\/a>.<\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"Pros_and_Cons\"><\/span>Pros and Cons<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<h4>Pros<\/h4>\n<ul>\n<li>A new operation (visitor) can be easily added to the operations hierarchy<\/li>\n<li>An operation is encapsulated in one visitor<\/li>\n<li>You can build a state while traversing the object hierarchy<\/li>\n<\/ul>\n<h4>Cons<\/h4>\n<ul>\n<li>Modifying the object hierarchy with a new visited object <code>VisitedObject<\/code> is hard\n<ul>\n<li>You have to add or remove the visited object (<code>VisitedObject<\/code>) from the object hierarchy<\/li>\n<li>You have to extend the interface of the visitor and add or remove the <code>visit(VisitObject)<\/code> member function to each concrete visitor<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>The complicatedness of the Visitor Pattern is mainly for one reason: double dispatch<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Single_Dispatch_and_Double_Dispatch\"><\/span>Single Dispatch and Double Dispatch<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Before I write about double dispatch, let me write about single dispatch, commonly known as virtual function calls.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Single_Dispatch\"><\/span>Single Dispatch<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In a single dispatch, the object decides which member function is called. To get virtuality in C++, you need two ingredients. An indirection such as a pointer or a reference and a virtual member function.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ singleDispatch.cpp<\/span>\n\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Ball<\/span> {\n <span style=\"color: #9999ff;\">public:<\/span>\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> std<span style=\"color: #555555;\">::<\/span>string getName() <span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;\n    <span style=\"color: #006699;\">virtual<\/span> ~Ball() = default;\n};\n\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">HandBall<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Ball {\n    std<span style=\"color: #555555;\">::<\/span>string getName() <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #cc3300;\">\"HandBall\"<\/span>;\n    }\n};\n\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>() {\n\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n\n    HandBall hBall;\n\n    Ball<span style=\"color: #555555;\">*<\/span> ballPointer <span style=\"color: #555555;\">=<\/span> <span style=\"color: #555555;\">&amp;<\/span>hBall;                         <em><span style=\"color: #0099ff;\">\/\/ (1)<\/span><\/em>\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"ballPointer-&gt;getName(): \"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> ballPointer<span style=\"color: #555555;\">-&gt;<\/span>getName() <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n\n    Ball<span style=\"color: #555555;\">&amp;<\/span> ballReference <span style=\"color: #555555;\">=<\/span> hBall;                        <em><span style=\"color: #0099ff;\">\/\/ (2)<\/span><\/em>\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"ballReference.getName(): \"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> ballReference.getName() <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n\n}\n<\/pre>\n<\/div>\n<p>The expression <code>Ball* ballPointer = &amp;hBall<\/code> (line 1) has two types. The static type (<code>Ball*<\/code>) and the dynamic type (<code>Handball*<\/code>), return by the address of the operator <code>&amp;<\/code>. Because of the virtuality of the member function getName, the member function call is looked up at the run time. Consequentially, a dynamic dispatch happens, and the member function <code>getName<\/code> is called. A similar argumentation holds for the reference used in line (2).<\/p>\n<p>Here is the output of the program:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6485\" style=\"display: block; margin-left: auto; margin-right: auto;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/singleDispatch.png\" alt=\"singleDispatch\" width=\"400\" height=\"207\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/singleDispatch.png 450w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/singleDispatch-300x155.png 300w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<p>Now, let&#8217;s analyze the double dispatch used in the Visitor Pattern.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Double_Dispatch\"><\/span>Double Dispatch<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In double dispatch, it depends on two objects, which operation is performed.<\/p>\n<p>This means, in the concrete case of the program <code>visitor.cpp<\/code>, that the visitor and visited object manage together to call the appropriate member function.<\/p>\n<p>To make it concrete: What happens in the call\u00a0<code>car.accept(carElementDoVisitor)<\/code> (line 4)? For simplicity, here is the member function <code>accept<\/code>.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">accept<\/span>(CarElementVisitor<span style=\"color: #555555;\">&amp;<\/span> visitor) <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\n    <span style=\"color: #006699; font-weight: bold;\">for<\/span> (<span style=\"color: #006699; font-weight: bold;\">auto<\/span> elem <span style=\"color: #555555;\">:<\/span> elements) {\n        elem<span style=\"color: #555555;\">-&gt;<\/span>accept(visitor);\n    }\n    visitor.visit(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>);\n}\n<\/pre>\n<\/div>\n<ol>\n<li>The member function <code>accept<\/code> of car iterates through all elements and calls <code>elem-&gt;accept(visitor)<\/code> on them: <code>elem<\/code> is a pointer and <code>accept<\/code> a virtual function =&gt; dynamic dispatch<\/li>\n<li>Finally, the visitor calls <code>visit<\/code> on itself, using the visited element as an argument:<code> visitor.visit(*this).<\/code> Consequentially, the appropriate overload of the visitor is called =&gt; static dispatch<code><br \/>\n<\/code><\/li>\n<\/ol>\n<p>Double dispatch, in the case of the visitor, is a ping\/pong game between the element (car element) and the visitor. The car element applies a dynamic dispatch (override), and the visitor a static dispatch (overload).<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Whats_Next\"><\/span>What&#8217;s Next?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The <a href=\"https:\/\/en.wikipedia.org\/wiki\/Template_method_pattern\">Template Method<\/a> is a behavioral design pattern that defines a template of an algorithm. In C++, we use a special variant of it: <a href=\"https:\/\/en.wikipedia.org\/wiki\/Non-virtual_interface_pattern\">Non-Virtual Interface (NVI)<\/a>. I will present the Template Method in my next post.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Visitor Pattern encapsulates an operation executed on an object hierarchy as an object and enables it to define new operations without changing the object hierarchy.<\/p>\n","protected":false},"author":21,"featured_media":6479,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[379],"tags":[],"class_list":["post-6486","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-patterns"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6486","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=6486"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6486\/revisions"}],"predecessor-version":[{"id":8015,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6486\/revisions\/8015"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/6479"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=6486"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=6486"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=6486"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}