How to cast a vector of struct to a vector of 'base' struct

I have :
1
2
3
4
5
6
7
8
9
struct A {
 int value1;
 int value2;
}

struct B : A {
 int value3;
 int value4;
}


I have vector<B> my_vector; and a function that receives vector<A>

I can create a copy of my_vector with A data using a loop.
The question is : is there some kind to cast the whole vector ?
(I think that it is not possible but .... )

Thanks


If you do the copy as you say you do, you'll incur in object slicing (google it up). Polymorphism can only be achieved via pointers or references. Since you say your have a vector of B structs, you'll have to create a vector<A*> from your vector<B>.

1
2
3
4
5
6
7
8
vector<B> myVector;
//Initialize vector with items, then:
vector<A*> myPtrs;
for (vector<B>::const_iterator it = myVector.begin(); it < myVector.end(); it++)
{
    myPtrs.push_back(it); //Might require casting or changing to &(*it).
}
//Now myPtrs is ready to be used. 
Ok, thanks.
The initial doubt is still on the air.
Is there then impossible to make 'some cast' over the whole vector ?
I have, in example, 100 bytes for each item, and I have a function that would receive 30 bytes for each item ( struct A has 30 struct B 30 +70 ) ?
Thanks again.
Topic archived. No new replies allowed.