I have read in many different posts regarding this matter, that arrays are not to be treated polymorphically and that one should use arrays of pointers instead, and the reasoning behind it is clear to me.
However, I cannot find an example of how it is done and I cannot seem to get it working. Consider the following piece of code:
#include <vector>
class Base
{
public:
Base();
virtual ~Base();
};
class Derived : Base
{
public:
Derived();
~Derived();
};
void foo( std::vector<Base*> )
{
// do something
}
int main()
{
std::vector<Derived*> bar;
foo(bar);
return 0;
}
Compiling this gives the error message
could not convert 'bar' from 'std::vector<Derived*>' to 'std::vector<Base*>
Am I missing something or is the design even fundamentally flawed? Thanks in advance.
std::vector<Derived*>
andstd::vector<Base*>
are different types and there are no conversions between them. But it looks like what you need isi.e. let the polymorphism work at the level of the elements of the vector.
However, note that in order to use polymorphism in the usual sense,
Derived
has to inherit publicly fromBase
:or