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);
}
};
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);
}
};
You can not instantiate a class which has a pure virtual function like this:
virtual void yourFunction() = 0
Make a subclass or remove it.
Only concrete class can be instancied. Func should be not pure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With