I want to implement a copy constructor on the following class A which contains a pointer to a polymorphic implementation class Base. At present, I have a virtual create_copy() method in class Base that derived classes need to override. However, the overrides for the derived classes all use the exact same code. Am I missing an easier way to copy objects of type A? And do I really need to replicate the exact same code for each derived class? The following is what I am using now. In case it changes the answer, runtime polymorphism is required.
class A {
public:
A(const A& a): base_p {a.base_p->create_copy()} {}
private:
unique_ptr<Base> base_p;
};
class Base {
public:
virtual unique_ptr<Base> create_copy() const;
};
class Derived : public Base {
public:
unique_ptr<Base> create_copy() const override {
return make_unique<Derived>(*this);
}
};
One idea I had involved using some code like:
return make_unique<remove_reference_t<decltype(*this)>>(*this);
However, this code does not work in a const member function. Also I think I would still have to explicitly override the create_copy() method in each derived class since decltype(*this) is evaluated at compile time, and therefore putting that code into the base class method would not do me any good.
EDIT: The answer at Inheritance in curiously recurring template pattern polymorphic copy (C++) is more complicated than what I needed. I have a simple inheritance hierarchy of depth 1 that should never need to be expanded to greater depth. Iorro's answer along with the provided link was sufficient to solve my problem.