Which situation will use clone in C++ and how to use it?

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();

Upvotes: 1

Views: 3714

Answers (2)

Colin
Colin

Reputation: 3752

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.

Upvotes: 4

Beta
Beta

Reputation: 99144

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".

Upvotes: 2

Related Questions