How to use clone() in C++ with multiple inheritance of abstract classes?

廉价感情. 提交于 2019-12-05 21:51:36

The idea would be to have a protected virtual method clone_impl in Base and a public non-virtual clone:

class Base
{
protected:
    virtual Base* clone_impl() const = 0;

public:
    Base* clone() const
    {
      return clone_impl();
    }
};

and for each derived class provide clone_impl when the class is not abstract and a non-virtual wrapper clone for all derived classes:

class DerivedX : ...
{
protected:
    // only when not abstract:
    virtual Base* clone_impl() const
    {
      return new DerivedX(*this);
    }

public:
    // in each derived class
    DerivedX* clone() const
    {
      return static_cast<DerivedX*>(clone_impl());
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!