Automatic Conversion of STL Containers: e.g. from vector<derived*> to vector<base*>

C

CD

Is this possible:

class base;
class derived; //:public base

vector <base*> bList;
vector<derived*> dList;

//add some derived class pointer entries to dList;

bList = dList;
//OR bList = (vector <base*>) dList;

//use the entries as base class pointers


- CD
 
I

Ivan Vecerina

CD said:
Is this possible:

class base;
class derived; //:public base

vector <base*> bList;
vector<derived*> dList;

//add some derived class pointer entries to dList;

bList = dList;
No: assignment will only work if both vectors have the same type.
//OR bList = (vector <base*>) dList;
No: something similar *might* work in practice, but would be UB
(undefined behavior).

The modified code below will work, however:

#include <vector>
using namespace std;

class Base {};
class Derived : public Base {};

void f( vector<Derived*> const d, vector<Base*>& b )
{
b.assign( d.begin(), d.end() ); // ok, copies & converts the pointers
// b now has a (converted) copy of the contents of b
}


hth,
Ivan
 
V

Victor Bazarov

CD said:
Is this possible:

class base;
class derived; //:public base

vector <base*> bList;
vector<derived*> dList;

//add some derived class pointer entries to dList;

bList = dList;
//OR bList = (vector <base*>) dList;

//use the entries as base class pointers

Yes, it is possible. Since 'derived*' is convertible to 'base*',
a simple 'std::copy' should suffice:

std::copy(dList.begin(), dList.end(), std::back_inserter(bList));

Since vector<base*> and vector<derived*> are not the same type, and even
not related, an assignment cannot work.

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,176
Messages
2,570,950
Members
47,503
Latest member
supremedee

Latest Threads

Top