M
Mr. Ed
I have a base class which has about 150 derived classes. Most of the
derived classes are very similar, and many don't change the base class
at all. All the derived classes have a unique factory method which
returns a new object of the derived type.
The problem I've got is that I now need to polymorphically clone a
derived class object, but I don't want to write a separate 'clone'
method for each of these 150 classes. Instead, I thought I might get
away with just writing one base class clone routine instead, something
like this pseudo-code:
BaseClass BaseClass::clone() {
BaseClass obj = this->factory(); // line 1
obj = *this; // line 2
return obj;
}
The rationale is that:
(line 1) 'obj' is correctly created as a derived-class object, because
'this->factory()' calls the polymorphic derived-class factory method
(line 2) 'obj = *this' uses the default copy assignment operator in a
given derived class to copy all the derived-class members to 'obj'.
This doesn't work, however, because the compiler doesn't know which
operator= to use in line 2. Basically, line 2 is asking for a
polymorphic assignment.
Is this code fixable? Is there any way to do this without writing 150
clone routines?
Thanks -
Ed
derived classes are very similar, and many don't change the base class
at all. All the derived classes have a unique factory method which
returns a new object of the derived type.
The problem I've got is that I now need to polymorphically clone a
derived class object, but I don't want to write a separate 'clone'
method for each of these 150 classes. Instead, I thought I might get
away with just writing one base class clone routine instead, something
like this pseudo-code:
BaseClass BaseClass::clone() {
BaseClass obj = this->factory(); // line 1
obj = *this; // line 2
return obj;
}
The rationale is that:
(line 1) 'obj' is correctly created as a derived-class object, because
'this->factory()' calls the polymorphic derived-class factory method
(line 2) 'obj = *this' uses the default copy assignment operator in a
given derived class to copy all the derived-class members to 'obj'.
This doesn't work, however, because the compiler doesn't know which
operator= to use in line 2. Basically, line 2 is asking for a
polymorphic assignment.
Is this code fixable? Is there any way to do this without writing 150
clone routines?
Thanks -
Ed