Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting from vector<derived>::iterator to vector<base>::iterator

Is it possible to do the operation described in the title? Here is a concrete example of what I want to do:

#include <vector>
class Base{
public:
    Base(int t){tst = t;}
protected:
    int tst;
};

class Derived : public Base{
public:
    Derived(int t):Base(t){} 
};

int main(){
    std::vector<Derived> test;
    test.push_back(Derived(1));
    std::vector<Base>::iterator iTest = test.begin();
}

The last line fails. using static_cast doesn't work either. Is there a good way to do this? How could I iterate over a vector of derived class objects as a vector of base class objects otherwise?

like image 356
c.hughes Avatar asked Jun 25 '26 07:06

c.hughes


1 Answers

You can not convert them together.

I think you need something like this:

std::vector<Base*> test;
test.push_back( new Derived(1) );

std::vector<Base*>::iterator iTest = test.begin();

// ....

// cleanup 

And then enjoy the polymorphism advantages.

like image 172
masoud Avatar answered Jun 26 '26 23:06

masoud