I am learning C++ and our teacher ask us to use a copy function with a pointer. He gave us a similar code to this one but I can't figure out how to use the copy function:
class Animal
{
public:
...
virtual Animal* copy() const =0;
}
class Dog : public Animal
{
public:
...
virtual Animal* copy() const;
}
Animal* Dog::copy() const
{
return new Dog(*this);
}
int main(){
Dog husky (…);
//Labrador = copy() of husky
}
For example, what should I write to create a new objet (labrador) as a copy of an object (husky)?
Thanks
In this case, you don't actually need to use that copy()
method at all, because you know that your husky
object is a Dog
and you want the copy to be another Dog
. So you can just write
Dog labrador(husky)
to construct labrador
as a copy of husky
using its copy constructor.
The point of the copy()
method is that sometimes you just have an Animal*
and you don't actually know what concrete type of animal it points to, so you don't know what type of new animal to create. For example:
void example(Animal const *animal) {
Animal *clonedAnimal = animal->copy();
}
The example
function doesn't know what kind of Animal
it's been given, but the animal object itself knows what it is, and the virtual function call lets that animal take care of copying itself. If animal
points to a Dog
instance, the Dog
version of copy()
will run and construct a Dog
. If animal
points to a Cat
, the Cat
version of the function will run and construct a new Cat
.