casting an vector::iterator to a derived type to the base class

P

propokergrad

Hello, say I have two classes:

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

I would like to do something similar to this:

std::vector<Base*>::iterator b;
std::vector<Derived*>::iterator d;

d = vector_of_derived.begin();
b = *((std::vector<Base*>::iterator*)(&d));

Am I correct that this a really stupid thing to do? Is there a better
way of going about this? Thanks for any help!

-Mike
 
R

red floyd

Hello, say I have two classes:

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

I would like to do something similar to this:

std::vector<Base*>::iterator b;
std::vector<Derived*>::iterator d;

d = vector_of_derived.begin();
b = *((std::vector<Base*>::iterator*)(&d));

Am I correct that this a really stupid thing to do? Is there a better
way of going about this? Thanks for any help!

don't even bother with the d variable.

Base* b_ptr = *b;
Derived* d_ptr = dynamic_cast<Derived*>(b_ptr);

But is there a reason you need to know if it's a Base or Derived in this
situation? If so, then you probably should have two containers,
otherwise, just rely on polymorphic behavior in Base.
 
I

Ian Collins

Hello, say I have two classes:

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

I would like to do something similar to this:

std::vector<Base*>::iterator b;
std::vector<Derived*>::iterator d;

d = vector_of_derived.begin();
b = *((std::vector<Base*>::iterator*)(&d));

Am I correct that this a really stupid thing to do? Is there a better
way of going about this? Thanks for any help!
Yes, it is really stupid thing to do! Iterators are unrelated types, so
casting between different iterators is not a good idea.

Why not just use a vector of Base*?
 
P

propokergrad

Here's my issue. I have a vector<Derived*>, and an interface that
takes a vector<Base*>::iterator. Is there something as a proxy
iterator class that will do the conversion automatically?
 
I

Ian Collins

(e-mail address removed) wrote:

Please don't top-post.
Here's my issue. I have a vector<Derived*>, and an interface that
takes a vector<Base*>::iterator. Is there something as a proxy
iterator class that will do the conversion automatically?

Not easily, no. The iterators are different types.

Can't you change the vector<Derived*> to a vector<Base*>?
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top