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
requiresreinterpret_cast, C-style cast or function-style cast
If C is a descendant of A, why is this happening?
While
Cis derived fromA,std::vector<C*>isn’t derived fromstd::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:
However, of course the following is possible:
Here, we create a new vector
v2and copy the elements ofv1into it. This is possible becauseCis derived fromA.