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

后端 未结 2 1417
粉色の甜心
粉色の甜心 2021-01-24 12:04

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 B         


        
相关标签:
2条回答
  • 2021-01-24 12:20

    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.

    0 讨论(0)
  • 2021-01-24 12:32

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

    0 讨论(0)
提交回复
热议问题