Can I pass a pointer to a superclass, but create a copy of the child?

霸气de小男生 提交于 2019-11-28 05:18:09

问题


I have a function that takes a pointer to a superclass and performs operations on it. However, at some point, the function must make a deep copy of the inputted object. Is there any way I can perform such a copy?

It occurred to me to make the function a template function and simply have the user pass the type, but I hold out hope that C++ offers a more elegant solution.


回答1:


SpaceCowboy proposes the idiomatic clone method, but overlooked 3 crucial details:

class Super
{
public:
  virtual Super* clone() const { return new Super(*this); }
};

class Child: public Super
{
public:
  virtual Child* clone() const { return new Child(*this); }
};
  1. clone is a const method
  2. clone returns a pointer to the current class, not the base class
  3. clone returns a copy of the current object

The 2nd is very important, because it allows use to benefit from the fact that sometimes you have more type information than just a Super*.

Also, I usually prefer clone to provide a copy, and not merely a new object of the same type. Otherwise you're using an Exemplar pattern to build new objects, but you're not cloning proper and the name is misleading.




回答2:


One example I've seen in wxWidgets is defining a overriden method 'clone' so that in each class you can make the appropriate deep copy but the method returns the copy as the superclass.

(and then there where other answers with examples)



来源:https://stackoverflow.com/questions/3063534/can-i-pass-a-pointer-to-a-superclass-but-create-a-copy-of-the-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!