title: Dynamic cast to derived type in operator<<
body: <p>I have a base class <code>Tag</code> and a child class <code>TagSet</code>, that inherits from <code>Tag</code>.</p>
  
  <pre><code>class Tag
  {
    public:
      Tag(std::string);
      std::string tag;
  };
  std::ostream &amp; operator &lt;&lt;(std::ostream &amp;os, const Tag &amp;t);
  
  class TagSet : public Tag
  {
  public:
      TagSet();
  };
  std::ostream &amp; operator &lt;&lt;(std::ostream &amp;os, const TagSet &amp;ts);
  </code></pre>
  
  <p>and their implementations</p>
  
  <pre><code>Tag::Tag(std::string t)
  : tag(t)
  {}
  
  std::ostream &amp; operator &lt;&lt;( std::ostream &amp;os, const Tag &amp;t )
  {
    os &lt;&lt; "This is a tag";
    return os;
  }
  
  TagSet::TagSet()
  : Tag("SET")
  {}
  
  std::ostream &amp; operator &lt;&lt;(std::ostream &amp;os, const TagSet &amp;ts)
  {
    os &lt;&lt; "This is a TagSet";
    return os;
  }
  </code></pre>
  
  <p>I want to include a third class <code>TagList</code> that has a member <code>std::vector&lt;Tag*&gt;</code>, which can hold either <code>Tag*</code> instances or <code>TagSet*</code> instances. I want to define the <code>&lt;&lt;</code> operator for <code>TagList</code> such that it uses the <code>Tag</code> version of <code>operator&lt;&lt;</code> if the element is a <code>Tag</code> or the <code>TagSet</code> version of <code>operator&lt;&lt;</code> if the element is a <code>TagSet</code>. This is my attempt:</p>
  
  <pre><code>std::ostream &amp; operator &lt;&lt;(std::ostream &amp;os, const TagList &amp;ts)
  {
    for (auto t : ts.tags)
    {
      if (t-&gt;tag == "SET")
      {
        TagSet * tset = dynamic_cast&lt;TagSet*&gt;(t);
        os &lt;&lt; *tset &lt;&lt; ", ";
      }
      else os &lt;&lt; t-&gt;tag &lt;&lt; ", ";
    } 
  }
  </code></pre>
  
  <p>The code crashes at runtime. I checked the <code>tset</code> pointer and it isn't null. Probably it's a bad cast.</p>
  
  <p>What is the correct way to do this? Is the problem something to do with consts in the <code>operator&lt;&lt;</code> function? Other suggests for how to achieve this are welcome.</p>
  
  <p>The rest of the <code>TagList</code> implementation is here for completeness:</p>
  
  <pre><code>class TagList
  {
  public:
      TagList(std::vector&lt;Tag*&gt; taglist);
      std::vector&lt;Tag*&gt; tags;
      typedef std::vector&lt;Tag*&gt;::const_iterator const_iterator;
      const_iterator begin() const { return tags.begin(); }
      const_iterator end() const { return tags.end(); }
  };
  std::ostream &amp; operator &lt;&lt;(std::ostream &amp;os, const TagList &amp;ts);
  </code></pre>
  
  <p>and</p>
  
  <pre><code>TagList::TagList(std::vector&lt;Tag*&gt; tagvec)
  : tags(tagvec.begin(), tagvec.end())
  {}
  </code></pre>