I have a data structure that accepts an abstract class in the c’tor. I’d like to copy the class (via clone method) to one of the data structure’s private fields so I don’t have to keep storing it outside the structure.
I’ve found this explanation on cplusplus.com by jsmith:
// Depending upon your needs, you might not require a base class
// clonable concept. It would only be needed if you need to store
// clonable objects polymorphically.
struct clonable {
virtual ~clonable() {}
virtual clonable* clone() const = 0;
};
class Base : public clonable {
public:
virtual Base* clone() const
{ return new Base( *this ); }
};
class Derived : public Base {
public:
virtual Derived* clone() const
{ return new Derived( *this ); }
};
Here’s what I have so far:
template <class T>
class AbstractBase {
public:
virtual AbstractBase<T>* clone() const = 0;
virtual int operator()(const T& lhs, const T& rhs) const = 0;
};
template <class T>
class Derived : public AbstractBase<T> {
public:
Derived* clone() { return new Derived(*this); } /* ERROR: can't instantiate abstract class */
int operator()(const T& lhs, const T& rhs) const { return something; }
};
template <class T>
class DataStructure {
public:
DataStructure(AbstractBase<T>* base) : base(base->clone()) {}
//...
private:
AbstractBase<T>* base;
}
I realise it’s calling the c’tor of AbstractBase. Is there an elegant and/or simple way to fix this while keeping AbstractBase abstract?
You need to override
Note the
const.