I am apologize if it is a stupid problem.
I want to do deep copy of a derived class.
I have do a search and found there already exist the topic.
C++: Deep copying a Base class pointer
Copying derived entities using only base class pointers, (without exhaustive testing!) - C++
Some elegant advice has been given, such as using virtual copy pattern
.
struct base {
virtual ~base() {} // Remember to provide a virtual destructor
virtual base* clone() const = 0;
};
struct derived : base {
virtual derived* clone() const {
return new derived(*this);
}
};
In my case, I do not want to use the pointer. I do not know can we do something similar via reference?
Suppose a base class should define a deepCopy interface, to make sure all derived class can do deep copy.
class Base
{
public:
virtual Base &deepCopy() = 0; // may be not good practice, you can change the deep copy interface
virtual void doSomeThing() = 0;
};
and the derived class may be something like this,but I have no idea how to write that.
class Derived : public Base
{
public:
// should overide interface, and I have no idea how to do that.
Base &deepCopy() override
{
}
void doSomeThing() override
{
// Omitted
}
// do shallow copy
Derived& operator=(const Derived&rhs)
{
// omitted
return (*this);
}
private:
int size;
double *data;
};
If you have good idea, change base interface is ok, as long as not using pointer.
I want using deep copy by follow way:
Derived a;
Derived b = a.deepCopy();
Thanks for your time.
edit
Thanks many advice have been given on the comment. Thanks for your all time.
I am rethink my problem.
I want
(1) polymorphism
(2) enforce derived class implement deepCopy interface.
(3) a =
interface for shallow copy and a deepCopy
interface for deep copy.
Actually, pointer solution can settle (1),(2),(3) while template solution from walnut can settle (2)(3). They are all good enough.
I am still confused that how to using reference to relize (1)(2)(3) above. May be it is a solution solve the (1)(2)(3) in another pespective.
I am now wonder if it is my fault that I am too adhere to reference ...