1

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.

Community
  • 1
  • 1
Jim Vargo
  • 362
  • 1
  • 8
  • You may be interested in [this post](https://stackoverflow.com/questions/196733/how-can-i-use-covariant-return-types-with-smart-pointers) – Cory Kramer Jun 17 '16 at 18:15
  • Possible duplicate of [Inheritance in curiously recurring template pattern polymorphic copy (C++)](http://stackoverflow.com/questions/9422760/inheritance-in-curiously-recurring-template-pattern-polymorphic-copy-c) – m.s. Jun 17 '16 at 18:15
  • Does the design really need a `unique_ptr`, where the content gets cloned at every copy !? –  Jun 17 '16 at 18:21
  • @Dieter The implementation classes maintain their own state. And the copies need to have an independent copy of that state. – Jim Vargo Jun 17 '16 at 18:24
  • Also of interest; http://stackoverflow.com/a/24951629/3747990 – Niall Jun 17 '16 at 18:29

1 Answers1

2
  • Have an intermediate BaseImplCopy template class
  • Implement create_copy() for T in it
  • Make it derive from Base
  • Let Derived derive from BaseImplCopy

This is called CRTP and is used widely. Note that you might need to static_cast(this) in BaseImplCopy.

Btw, create_copy() is conventionally called clone().

lorro
  • 10,687
  • 23
  • 36