peskal
peskal

Reputation: 1223

Passing a list of derived classes to a function expecting a list of base classes in C++

I have the following classes

class Parent {
  virtual void doStuff() = 0;
};

class Child : public Parent {
  void doStuff() {
    // Some computation here
  }
};

And I have a function with the following signature.

void computeStuff(std::vector<boost::shared_ptr<Parent> >);

Provided I can refactor my code (including the function signature), what is the best way to pass the function computeStuff a list of pointers to Child objects?

Essentially, I would like the following snippet of code to compile and run

std::vector<boost::shared_ptr<Child> > listOfChilds = getList();
computeStuff(listOfChilds);

Upvotes: 1

Views: 413

Answers (1)

James McNellis
James McNellis

Reputation: 355177

The "best" way would be to have the function take a pair of iterators:

template <typename ForwardIterator>
void computeStuff(ForwardIterator first, ForwardIterator last) {
    /* ... */
}

You can call this function as:

std::vector<boost::shared_ptr<Child> > listOfChilds = getList();
computeStuff(listOfChilds.begin(), listOfChilds.end());

There are a lot of advantages to taking a pair of iterators instead of a container, but the two big ones here are that

  • the computeStuff function can take a range from any type of container, not just a std::vector, and

  • the range just has to contain objects that are convertible to the type that you want to use (e.g. boost::shared_ptr<Parent>), it doesn't actually have to contain objects of that specific type.

Upvotes: 5

Related Questions