Taylor Huston
Taylor Huston

Reputation: 1150

Call an overloaded << operator on a derived class in a vector

Assuming you've implemented the << operator correctly, how can you properly call it on a vector of derived classes?

Say you've got class Base, and from it DerivedOne, DerivedTwo, etc. Then in your main you have a vector of pointers to various derived type objects. Something along the lines of:

void showItems(vector<Base*>  items) {
    for (int i = 0; i < items.size(); i++) {
        cout << items[i];
    }
    cout << endl;
}

Upvotes: 0

Views: 78

Answers (1)

John Zwinck
John Zwinck

Reputation: 249642

Implement something like this:

class Base
{
public:
  virtual ostream& print(ostream&) const = 0;
};

ostream& operator <<(ostream& out, const Base& base)
{
  return base.print(out);
}

Upvotes: 7

Related Questions