This seems like a pretty basic problem, but I can\'t figure it out. I have a std::vector
of raw pointers to Derived objects, and I just want to copy it to anot
push_back
performs element-wise conversions. The assignment operator exists only between vectors of the same type.
An easy solution is to use assign
:
v2.assign(v1.begin(), v1.end());
In the general case of templates, if you have a class template
template <typename T> struct Foo {};
Foo<Base>
is not a base class of Foo<Derived>
.
Hence, you cannot do:
Foo<Derived> f1;
Foo<Base> f2 = f1;
That's because while Base
and Derived
have a relationship, there is no relationship between vector<Base*>
and vector<Derived*>
. As far as class hierarchy is concerned, they are entirely unrelated, so you can't assign one to the other.
The concept you are looking for is called covariance. In Java for instance, String[]
is a subtype of Object[]
. But in C++, these two types are just different types and are no more related than String[]
and Bar
.
push_back
works because that method just takes a T const&
(or T&&
), so anything convertible to a Base*
will be acceptable - which a Derived*
is.
That said, vector
has a constructor that takes a pair of iterators, which should be easier to use here:
vector<Base*> v2(v1.begin(), v1.end());
Or, since it is already constructed:
v2.assign(v1.begin(), v1.end());