Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign vector of children to vector of grandparents

Tags:

c++

So I have the following classes:

class A {}
class B : public A {}
class C : public B {}

When I try do the following, I get an error:

vector<C*> v1; //already instantiated with a vector of pointers to C.
vector<A*>* v2 = &v1;

error C2440: 'initializing' : cannot convert from 'std::vector<_Ty> *'
to 'std::vector<_Ty> *' Types pointed to are unrelated; conversion
requires reinterpret_cast, C-style cast or function-style cast

If C is a descendant of A, why is this happening?

like image 587
Gerardo Avatar asked Dec 28 '25 16:12

Gerardo


1 Answers

While C is derived from A, std::vector<C*> isn't derived from std::vector<A*>, so you can't assign the address of an object of the former type to a pointer for the latter.

Imagine what would become possible if you could do this:

vector<A*>* v2 = &v1;

/* *v2 is declared as a vector<A*> so we can do this: */
v2->push_back(new B);

/* Now we have effectively added a pointer to a B object
   to the vector v1, which is supposed to be a vector of
   C objects only! */

However, of course the following is possible:

int main()
{
  std::vector<C*>  v1;
  std::vector<A*>  v2(begin(v1),end(v1));
  return 0;
}

Here, we create a new vector v2 and copy the elements of v1 into it. This is possible because C is derived from A.

like image 77
jogojapan Avatar answered Dec 30 '25 05:12

jogojapan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!