Suppose I have a base class Base
and a derived class Derived
as well as a std::vector<Base> vec(k)
that is being initialised with k
Base
instances.
How would I go about replacing instances of Base
with instances of Derived
while iterating over the vector?
If the classes were not hierarchically structured like ints I could just do this:
for (auto i = vec.begin(); i != vec.end();)
{
if (j == 3)
{
*i = 9;
}
else
{
++i;
}
}
But with derived and base classes this does not work, as this shows:
#include<iostream>
#include<vector>
#include<ostream>
class Base
{
public:
friend std::ostream& operator<<(std::ostream& o, Base& e)
{
return o << e.get_repr();
}
private:
virtual std::string get_repr()
{
return repr;
}
private:
std::string repr = "B";
};
class Derived: public Base
{
private:
std::string get_repr()
{
return repr;
}
private:
std::string repr = "D";
};
int main()
{
std::vector<Base> vec(5);
int j = 0;
for (auto i = vec.begin(); i != vec.end(); ++j)
{
if (j == 3)
{
*i = Derived();
}
else
{
++i;
}
}
for (auto i = vec.begin(); i != vec.end(); ++i)
{
std::cout << *i << ' ';
}
std::cout << std::endl;
}
the output being:
B B B B B
So how can I replace the Base
-instance with a Derived
-instance?
Edit
I changed the cell contents to pointers, as suggested in the comments. I did it like this:
int main()
{
std::vector<Base*> vec(5);
int j = 0;
for (auto i = vec.begin(); i != vec.end(); ++j)
{
if (j == 3)
{
*i = new Derived();
}
else
{
*i = new Base();
++i;
}
}
for (auto i = vec.begin(); i != vec.end(); ++i)
{
std::cout << **i << ' ';
}
std::cout << std::endl;
}
but I am still getting B B B B B
... why?