direct copy vs virtual copy constructor (clone function)

Viewed 70

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

1 Answers

The clone function is used with factories. These provide an object based on given input. An implementation is to have a map enums linked to each needed object known as the base class. So if your input specifies a red dog, you call the function Dog* getDog(enumDog newDog) and it gives you your needed object if it was provided to the map before.

An alternative for this is switch-case with all the enums.

Related