title: Testing Composite pattern in C++
body: <p>I was trying to test the Composite pattern example given in  <a href="https://en.wikipedia.org/wiki/Composite_pattern" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Composite_pattern</a> in C++, but the last statement in my main function is not working as expected. Can anyone give me some inputs?</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  class Graphic {
      public:
          virtual void print() {}
  };
  
  class Composite :  public Graphic {
      private:
          std::vector&lt;Graphic&gt; mGraphicList;
      public:
          void addGraphic(Graphic G) {
              std::cout &lt;&lt; &quot;ADDING ITEM&quot; &lt;&lt; std::endl;
              mGraphicList.push_back(G);
          }
          
          void print() {
               for (int i=0; i&lt;mGraphicList.size(); i++)
                  mGraphicList[i].print();
          }
  };
  
  class Ellipse : public Graphic {
      public:
          void print() {
              std::cout &lt;&lt; &quot;Ellipse&quot; &lt;&lt; std::endl;
          }
  };
  
  class Circle : public Graphic {
      public:
          void print() {
              std::cout &lt;&lt; &quot;Circle&quot; &lt;&lt; std::endl;
          }
  };
  
  int main()
  {
      Ellipse e1;
      e1.print();
      Circle c1;
      c1.print();
      std::cout &lt;&lt; &quot;__________________&quot; &lt;&lt; std::endl;
      Composite comp;
      comp.addGraphic(e1);
      comp.addGraphic(c1);
      
      comp.print();
  
      
      return 0;
  }
  </code></pre>
  <p>The output I am getting is:</p>
  <pre><code>Ellipse
  Circle
   __________________
  ADDING ITEM
  ADDING ITEM
  </code></pre>
  <p>but I was expecting:</p>
  <pre><code>Ellipse
  Circle
   __________________
  ADDING ITEM
  ADDING ITEM
  Ellipse
  Circle
  </code></pre>