Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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*>?

like image 421
andreas buykx Avatar asked Sep 22 '08 13:09

andreas buykx


1 Answers

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.

like image 103
ChrisN Avatar answered Sep 25 '22 23:09

ChrisN