maynard said:
I didn't type it wrong...
But it doesn't make sense.
I need to construct a new object based on what kind of object is stored in
the previous element (of base[]).
Unfortunately, if I pass *base[0] to a copy constructor, the only one
that will accept a reference to a Base object is the Base constructor
(since base[] is an array of pointers to Base). For instance, I can't
do this (which is what I really want):
base[2] = new D2(*base[0]);
So I *think* I'm forced to create a Base object and cast its pointer to
the derived class I need.
That doesn't magically convert the object into that derived class.
I've simplified this...in actuality, they're not all of type D2, some are
of D1 and some are of D3, but I only need to make a copy when they're of
type D2. Sorry, I know it's confusing.
And what do you want to do if it's not of type D2?
Anyway, the usual solution to copying polymorphic classes is a pure virtual
member function in Base, and its implementations in the derived classes
handle copying, like:
class Base
{
public:
virtual Base* clone() const = 0;
};
class D1: public Base
{
public:
virtual D1* clone() const
{
return new D1(*this);
}
};
class D2: public Base
{
public:
virtual D2* clone() const
{
return new D2(*this);
}
};
//...
Base* base[100];
base[0] = new D2;
base[2] = base[0]->clone();
Of course you can also make Base::clone a non-pure virtual function and
implement it similar to the ones in D1 and D2, if Base is not supposed to
be an abstract class.