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

2

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();
Provincial answered 10/10, 2011 at 2:54 Comment(2)
possible duplicate of C++ Virtual/Pure Virtual ExplainedTapster
See this answer in particular, where GetNumberOfLegs() is declared as virtual in the base class but not in derived classes.Tapster
W
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.

Westsouthwest answered 10/10, 2011 at 3:1 Comment(2)
which type do you mean? isn't the type Base?Provincial
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?Westsouthwest
G
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".

Greenwell answered 10/10, 2011 at 3:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.