I have base-class Base
from which is derived Derived1
, Derived2
and Derived3
.
I have constructed an instance for one of the the derived classes which I store as Base* a
. I now need to make a deep copy of the object which I will store as Base* b
.
As far as I know, the normal way of copying a class is to use copy constructors and to overload operator=
. However since I don't know whether a
is of type Derived1
, Derived2
or Derived3
, I cannot think of a way of using either the copy constructor or operator=
. The only way I can think of to cleanly make this work is to implement something like:
class Base
{
public:
virtual Base* Clone() = 0;
};
and the implement Clone
in in the derived class as in:
class Derivedn : public Base
{
public:
Base* Clone()
{
Derived1* ret = new Derived1;
copy all the data members
}
};
Java tends to use Clone
quite a bit is there more of a C++ way of doing this?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…