Getting a vector<Derived*> into a function that expects a vector<Base*>

andreas buykx picture andreas buykx · Sep 22, 2008 · Viewed 8k times · Source

Consider these classes.

class Base
{
   ...
};

class Derived : public Base
{
   ...
};

this function

void BaseFoo( std::vector<Base*>vec )
{
    ...
}

And finally my vector

std::vector<Derived*>derived;

I want to pass derived to function BaseFoo, but the compiler doesn't let me. How do I solve this, without copying the whole vector to a std::vector<Base*>?

Answer

ChrisN picture ChrisN · Sep 22, 2008

vector<Base*> and vector<Derived*> are unrelated types, so you can't do this. This is explained in the C++ FAQ here.

You need to change your variable from a vector<Derived*> to a vector<Base*> and insert Derived objects into it.

Also, to avoid copying the vector unnecessarily, you should pass it by const-reference, not by value:

void BaseFoo( const std::vector<Base*>& vec )
{
    ...
}

Finally, to avoid memory leaks, and make your code exception-safe, consider using a container designed to handle heap-allocated objects, e.g:

#include <boost/ptr_container/ptr_vector.hpp>
boost::ptr_vector<Base> vec;

Alternatively, change the vector to hold a smart pointer instead of using raw pointers:

#include <memory>
std::vector< std::shared_ptr<Base*> > vec;

or

#include <boost/shared_ptr.hpp>
std::vector< boost::shared_ptr<Base*> > vec;

In each case, you would need to modify your BaseFoo function accordingly.