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.

5

1 Answer 1

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

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.