Creating a copy of an abstract base class object

If I have a pointer to an object that comes from an abstract base class (so I canโ€™t create a new object of this class), and I want to make a deep copy of the specified object, there is a shorter way for the abstract base class to create a new clean virtual copy function that every inheriting class should implement?

+4
source share
3 answers

No, but the copy method should not be painful:

 class Derived : public Base { public: Base *copy() const { return new Derived(*this); } }; 

(suppose you already have a copy constructor, which, if you need a deep copy, you will have).

+9
source

The recommended "copy", commonly called the "clone", is the usual approach. An alternative could be a factory and dispatch using rtti to find the right handler, then call the copy constructor on the derived type.

 struct Abc { virtual void who() const = 0; }; struct A : Abc { virtual void who() const { std::cout << "A" << std::endl;} }; template<class T> Abc* clone(Abc* abc) { T* t = dynamic_cast<T*>(abc); if (t == 0) return 0; return new T(*t); } struct B : Abc { virtual void who() const { std::cout << "B" << std::endl;} }; typedef Abc* (*Cloner)(Abc*); std::map<std::string, Cloner> clones; void defineClones() { clones[ typeid (A).name() ] = &clone<A>; clones[ typeid (B).name() ] = &clone<B>; } Abc* clone(Abc* abc) { Abc* ret = 0; const char* typeName = typeid(*abc).name(); if (clones.find(typeName) != clones.end()) { Cloner cloner = clones[typeName]; ret = (*cloner)(abc); } return ret; } void test () { defineClones(); Abc* a = new A; Abc* anotherA = clone(a); anotherA->who(); Abc* b = new B; Abc* anotherB = clone(b); anotherB->who(); } 

While the above works, the factual fact that he uses rtti will be enough to convince most to take a normal approach. However, this was the reason for preventing changes in the base class, this may be useful.

Is it effective? The marginal cost of adding a new type is indeed one line. The trick is that it will be easy to forget to add this line with each new class. Or you can see this as a growth potential, that all the cloning code lives in one file, and we donโ€™t need to change the supported hierarchy to process it.

+1
source

A, when someone in comp.lang.C ++ asked how to automatically create the clone () function. Someone else presented an idea by which I expanded. None of them have been verified by code, and I have never tried it ... but I think it works: http://groups.google.com/group/comp.lang.c++/browse_thread/thread/c01181365d327b2f/9c99f46a8a64242e ? hl = en & ie = UTF-8 & oe = utf-8 & q = comp.lang.c% 2B% 2B + noah + roberts + clone & pli = 1

+1
source

Source: https://habr.com/ru/post/1336412/


All Articles