Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to assign vector of Base* from vector of Derived*

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 another vector of Base pointers using the assignment operator. With VC++ I get error C2679 "binary '=': no operator found..." BTW I don't want a deep copy of the objects, I just want to copy the pointers. Sample code:

#include <vector>
using namespace std;

struct Base{};    
struct Derived: public Base {};

int main (int argc, char* argv[])
{
    vector<Derived*> V1;
    vector<Base*> V2;
    V2 = V1;  //Compiler error here
    return 0;
}

What confuses me is that I can copy the vector by looping through it and using push_back, like this:

for (Derived* p_derived : V1)
    V2.push_back(p_derived);

So my question is why does the assignment fail, while push_back works? Seems like the same thing to me.

like image 692
Carlton Avatar asked Apr 07 '15 14:04

Carlton


3 Answers

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());
like image 66
Barry Avatar answered Nov 01 '22 12:11

Barry


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());
like image 25
Kerrek SB Avatar answered Nov 01 '22 12:11

Kerrek SB


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;
like image 37
R Sahu Avatar answered Nov 01 '22 11:11

R Sahu