Cloning C++ class with pure virtual methods

后端 未结 4 751
北海茫月
北海茫月 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);
        }
    };
    
    0 讨论(0)
  • 2021-01-18 07:09

    You can not instantiate a class which has a pure virtual function like this:

    virtual void yourFunction() = 0
    

    Make a subclass or remove it.

    0 讨论(0)
  • 2021-01-18 07:17

    I might be saying something stupid here, but I think that the clone method in the derived class should still return a pointer to the base class. Maybe it still compiles fine, but as far as maintainability of the code is concerned, I think is better to use the method clone only to return pointers to the base class. After all, if your derived class has to clone into a pointer to a derived class, you could as well just do

    Derived original;
    Derived* copy = new Derived(original)
    

    Of course, you need to implement the copy constructor, but that should usually be implemented anyway (except for extreme cases).

    0 讨论(0)
  • 2021-01-18 07:21

    Only concrete class can be instancied. Func should be not pure.

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