1

What is the difference between virtual clone and clone? I find the following example, it clone derived to base, what is it for?

class Base{
public:
    virtual Base* clone() {return new Base(*this);}
    int value;
    virtual void printme()
    {
        printf("love mandy %d\n", value);
    }
};
class Derived : public Base
{
public:
    Base* clone() {return new Derived(*this);}
    virtual void printme()
    {
        printf("derived love mandy %d\n", value);
    }
};

Derived der;
    der.value = 3;

    Base* bas = der.clone();
    bas->printme();
Daniel Daranas
  • 21,689
  • 9
  • 60
  • 108
M-Askman
  • 380
  • 4
  • 17
  • possible duplicate of [C++ Virtual/Pure Virtual Explained](http://stackoverflow.com/questions/1306778/c-virtual-pure-virtual-explained) – Johnsyweb Oct 10 '11 at 03:00
  • See [this answer](http://stackoverflow.com/questions/1306778/c-virtual-pure-virtual-explained/1307282#1307282) in particular, where `GetNumberOfLegs()` is declared as `virtual` in the base class but not in derived classes. – Johnsyweb Oct 10 '11 at 03:02

2 Answers2

4

Consider this:

Base * b = get_a_base_object_somehow();

// now, b might be of type Base, or Derived, or something else derived from Base

Base * c = b->clone();

// Now, c will be of the same type as b was, and you were able to copy it without knowing its type. That's what clone methods are good for.

Colin
  • 3,486
  • 1
  • 22
  • 31
  • which type do you mean? isn't the type Base? – M-Askman Oct 10 '11 at 04:20
  • That's what polymorphism is about. You might have a pointer to a Base, but the object might actually be of type Derived. So, get_a_base_object_somehow() might actually return something that inherits from Base. Which _is_ a Base, but it also is something else. Say Base=Car, and Derived=Convertible. Make sense? – Colin Oct 10 '11 at 13:56
2

Consider this:

Base* p1 = &der;
Base* p2 = p1->clone()
p2->printme();

If clone() is not virtual, the result will be "love mandy 3". If it is virtual, the result will be "derived love mandy 3".

Beta
  • 86,746
  • 10
  • 132
  • 141