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*>?
vector<Base*>andvector<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 avector<Base*>and insertDerivedobjects into it.Also, to avoid copying the
vectorunnecessarily, you should pass it by const-reference, not by value:Finally, to avoid memory leaks, and make your code exception-safe, consider using a container designed to handle heap-allocated objects, e.g:
Alternatively, change the vector to hold a smart pointer instead of using raw pointers:
or
In each case, you would need to modify your
BaseFoofunction accordingly.