Lets say that I have a base and derived class, and a function that takes an stl vector of pointers to the base class:
class A { public: int x; };
class B : public A { };
void foo(const vector<A*> &va) {
for (vector<A*>::const_iterator it = va.begin(); it < va.end(); it++)
cout << (*it)->x << endl;
}
is there any way to pass a list of pointers to the derived class? ie:
vector<B*> vb;
// ... add pointers to vb ...
foo(vb);
The above will cause the following compiler error:
error: could not convert ‘vb’ from ‘std::vector<B*>’ to ‘std::vector<A*>’
Even though B* is convertible to A*.
Finally, if there is a solution for plain pointers, will it work with boost shared pointers as well?
std::vector<B*> and std::vector<A*>
are technically unrelated. C++ does not allow what you want as such.
A way around...Why not have a std::vector<Base*>
and insert into it Derived
objects? That is the point of polymorphism, dynamic dispatch et al.
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