Home > Backend Development > C++ > body text

How to Deep Copy Derived Classes from Base Class Pointers?

DDD
Release: 2024-10-25 23:09:28
Original
636 people have browsed it

 How to Deep Copy Derived Classes from Base Class Pointers?

Creating Copies of Derived Classes from Base Class Pointers

Consider the challenge of creating a deep copy of a derived class instance from a pointer to its polymorphic base class. This can be tricky, as relying on multiple type IDs or dynamic casts in if-statements can become tedious and introduce performance implications.

A preferred approach involves incorporating a virtual method within the base class, known as clone() or copy(). This method should return a pointer to a newly created copy of the derived class. By implementing this method in each derived class, the copy process becomes independent of the specific derived class types.

Alternatively, to avoid code duplication, the Curiously Recurring Template Pattern (CRTP) idiom can be employed. Using a template, a helper class can be created that delegates the copy operation to the derived class constructor.

Implementation Using Clone() Method:

<code class="cpp">class Base {
  virtual Base* clone() const = 0;
};
class Derived1 : public Base {
  Base* clone() const { return new Derived1(*this); }
};
class Derived2 : public Base {
  Base* clone() const { return new Derived2(*this); }
};

Base* CreateCopy(Base* base) {
  return base->clone();
}</code>
Copy after login

Implementation Using CRTP Idiom:

<code class="cpp">template <class Derived>
class DerivationHelper : public Base {
public:
  Base* clone() const { return new Derived(static_cast<Derived&>(*this)); }
};

class Derived1 : public DerivationHelper<Derived1> { ... };
class Derived2 : public DerivationHelper<Derived2> { ... };</code>
Copy after login

The above is the detailed content of How to Deep Copy Derived Classes from Base Class Pointers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!