Cloning C++ class with pure virtual methods

我只是一个虾纸丫 提交于 2019-12-04 03:24:21

问题


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? Thanks.

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

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

回答1:


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);
    }
};



回答2:


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

virtual void yourFunction() = 0

Make a subclass or remove it.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/10586832/cloning-c-class-with-pure-virtual-methods

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