I have a base class `Tag` and a child class `TagSet`, that inherits from `Tag`.

```
class Tag
{
  public:
    Tag(std::string);
    std::string tag;
};
std::ostream & operator <<(std::ostream &os, const Tag &t);

class TagSet : public Tag
{
public:
    TagSet();
};
std::ostream & operator <<(std::ostream &os, const TagSet &ts);

```

and their implementations

```
Tag::Tag(std::string t)
: tag(t)
{}

std::ostream & operator <<( std::ostream &os, const Tag &t )
{
  os << "This is a tag";
  return os;
}

TagSet::TagSet()
: Tag("SET")
{}

std::ostream & operator <<(std::ostream &os, const TagSet &ts)
{
  os << "This is a TagSet";
  return os;
}

```

I want to include a third class `TagList` that has a member `std::vector<Tag*>`, which can hold either `Tag*` instances or `TagSet*` instances. I want to define the `<<` operator for `TagList` such that it uses the `Tag` version of `operator<<` if the element is a `Tag` or the `TagSet` version of `operator<<` if the element is a `TagSet`. This is my attempt:

```
std::ostream & operator <<(std::ostream &os, const TagList &ts)
{
  for (auto t : ts.tags)
  {
    if (t->tag == "SET")
    {
      TagSet * tset = dynamic_cast<TagSet*>(t);
      os << *tset << ", ";
    }
    else os << t->tag << ", ";
  } 
}

```

The code crashes at runtime. I checked the `tset` pointer and it isn't null. Probably it's a bad cast.

What is the correct way to do this? Is the problem something to do with consts in the `operator<<` function? Other suggests for how to achieve this are welcome.

The rest of the `TagList` implementation is here for completeness:

```
class TagList
{
public:
    TagList(std::vector<Tag*> taglist);
    std::vector<Tag*> tags;
    typedef std::vector<Tag*>::const_iterator const_iterator;
    const_iterator begin() const { return tags.begin(); }
    const_iterator end() const { return tags.end(); }
};
std::ostream & operator <<(std::ostream &os, const TagList &ts);

```

and

```
TagList::TagList(std::vector<Tag*> tagvec)
: tags(tagvec.begin(), tagvec.end())
{}

```