Cloning C++ class with pure virtual methods

后端 未结 4 806
北海茫月
北海茫月 2021-01-18 06:56

I have the following relation of classes. I want to clone the class Derived, but I get the error \"cannot instantiate abstract class\". How I can clone the derived class? T

4条回答
  •  没有蜡笔的小新
    2021-01-18 07:09

    Only concrete classes can be instantiated. You have to redesign the interface of Derived in order to do cloning. At first, remove virtual void func() = 0; Then you will be able to write this code:

    class Base {
    public:
        virtual ~Base() {}
        virtual Base* clone() const = 0;
    };
    
    class Derived: public Base {
    public:
        virtual Derived* clone() const {
            return new Derived(*this);
        }
    };
    

    Another solution is keeping pure virtual function in-place and adding a concrete class:

    class Base {
    public:
        virtual ~Base() {}
        virtual Base* clone() const = 0;
    };
    
    class Derived: public Base {
    public:
        virtual void func() = 0;
    };
    
    class Derived2: public Derived {
    public:
        virtual void func() {};
        virtual Derived2* clone() const {
            return new Derived2(*this);
        }
    };
    

提交回复
热议问题