Doug Mika <
doug...@gmail.com> wrote in
news:3bd1a60e-b37a-45c9...@googlegroups.com:
> Hi
>
> I have a base class called Fish, from this base class I derive two
> classes called Tuna and Carp
>
> I create a vector<Fish> into which I place new objects of Tuna and
> Carp. ie
> vector<Fish> vecOfFish;
> vecOfFish.push_back(new Tuna());
> vecOfFish.push_back(new Carp());
This does not compile. You have defined a vector of Fish objects, but are
pushing in pointers to objects instead of objects.
For getting polymorphic behavior you need a vector of some kind of
pointers. Instead of plain pointers better consider some kind of smart
pointers, e.g.
vector<std::shared_ptr<Fish>> vecOfFish;
vecOfFish.push_back(std::shared_ptr<Fish>(new Tuna()));
vecOfFish.push_back(std::shared_ptr<Fish>(new Carp()));
> ...
>
> Now I want to create a second vector of Fish
> vector<Fish> vecOfFish2;
>
> and copy the first vector into the second using std::copy.
>
> Which methods (copy constructor, copy assignment operator,....) must
> Carp and Tuna implement for the std::copy function to work properly
> (to perform a deep copy on my vector)?
For deep copy one needs to duplicate all the Tuna and Carp objects, given
only pointers to Fish. One typically implements this by declaring a
virtual clone function (look this up) in the base class. Both Carp and
Tuna must implement this and return a (smart)pointer to the cloned
object. The clone functions will typically make use of the copy
constructors.
std::copy() is probably not enough for getting deep copy (unless you use
a specific deep-copying smartpointer which does not seem very practical
otherwise). You will need to write a custom loop or use something like
std::transform().
hth
Paavo