P
Pat
Hi c.l.c++,
Suppose I have a fairly complex class hierarchy. All
the classes in the hierarchy have "child" pointers (one
or more) so that a big tree of these objects can be
built. But the catch is that each node in the tree can
be any type (in the hierarchy).
Now, I want to write a function to walk that tree and
create an exact copy of it. It's ok to assume that the
tree contains no loops.
I could write a fairly simple recursive function that
1) allocates a new object, 2) copies the old node's
data, and 3) calls itself for each child in the old
node.
But the trouble is in step 1, because I don't know what
type to allocate... My first thought was to use a
templated "clone" function, something like so:
template <class T>
T *clone(T *source)
{
T *dest = new T;
dest->x = source->x;
dest->y = sourec->y;
dest->z = source->z;
return dest;
}
But that doesn't work because as I'm walking the tree,
all of the "child" pointers are the same type (the base
class). And when I call clone() with a pointer to the
base class, it returns a pointer to the base class.
So, then, I thought that each derived class should have
a virtual clone() function that returns the appropriate
type. But then there's no way to call the correct
function at run-time. Each class's clone() function
would have a different return type.
I could have some sort of switch statement, I guess,
but that's ugly...
Suppose I have a fairly complex class hierarchy. All
the classes in the hierarchy have "child" pointers (one
or more) so that a big tree of these objects can be
built. But the catch is that each node in the tree can
be any type (in the hierarchy).
Now, I want to write a function to walk that tree and
create an exact copy of it. It's ok to assume that the
tree contains no loops.
I could write a fairly simple recursive function that
1) allocates a new object, 2) copies the old node's
data, and 3) calls itself for each child in the old
node.
But the trouble is in step 1, because I don't know what
type to allocate... My first thought was to use a
templated "clone" function, something like so:
template <class T>
T *clone(T *source)
{
T *dest = new T;
dest->x = source->x;
dest->y = sourec->y;
dest->z = source->z;
return dest;
}
But that doesn't work because as I'm walking the tree,
all of the "child" pointers are the same type (the base
class). And when I call clone() with a pointer to the
base class, it returns a pointer to the base class.
So, then, I thought that each derived class should have
a virtual clone() function that returns the appropriate
type. But then there's no way to call the correct
function at run-time. Each class's clone() function
would have a different return type.
I could have some sort of switch statement, I guess,
but that's ugly...