It has been two days I'm trying to understand why do we need clone function( virtual copy constructor).
I created a simple example (code below): :
#include <iostream>
class Dog
{
public:
Dog() { std::cout << "I am a Dog\n"; }
virtual Dog* clone() { return new Dog(*this); }
virtual void info() { std::cout << "info : I am a Dog\n";}
};
class RedDog : public Dog
{
public:
RedDog() {std::cout << "I am a RedDog\n"; }
RedDog* clone() { return new RedDog(*this); }
void info() { std::cout << "info : I am a RedDog\n"; }
};
void foo(Dog* pd)
{
Dog* temp = pd;
//Dog* temp = pd->clone();
temp->info();
}
int main()
{
Dog d;
std::cout << "########################\n";
RedDog rd;
std::cout << "########################\n";
foo(&rd);
return 0;
}
There is no difference between using clone in foo function and using normal copy. it will execute the function of appropriate object.
Please show me in an example simple that if I don't use clone there will be problem, or usage of clone.
Thanks