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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With