Re: Cloning members of a hierarchy
 
Paul N wrote:
I've got various classes derived (directly or indirectly) from a
single base, and want a function to make a copy of a given object. My
code is along the following lines:
class Base {
  public:
  int b;
  virtual Base *clone() = 0;
  };
class Derived : public Base {
  public:
  int d;
  Base *clone() { return new Derived(*this); }
  };
Am I right in thinking that I need to include a definition of the
"clone" function for every class that I want to be able to clone
objects of?
Yes.  In production code I often see a macro that does that.  Don't 
forget to write it in your class.  Something like
#define DEFINE_CLONABLE(class_name) class_name* clone() \
                                     { return new class_name(*this); }
....
    class Derived ...
      DEFINE_CLONABLE(Derived)
    };
 > And that this would be true even if I didn't make it a
pure virtual function?
If you didn't make it pure virtual, what would its body look like?
 > And that there is no easy way round this, short
of using macros to "tidy" the code up?
Not really.  Unless I'm missing something obvious, of course.
 > But conversely, am I right in
thinking that the automatically-generated copy constructors will do
the actual donkey work of making a copy of all the members at all the
levels for me?
Seems so.
(I was also going to include a question about a potential bug in VC++,
in which it complained about not being able to instatiate an abstract
class - but it turned out that the problem was that one declaration
was declared "const" and the other wasn't, so it was my fault.)
That would certainly do it. :-)
V
-- 
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask