Stefan Näwe wrote:
Tony Johansson wrote: Hello experts!
How is it possible to copy concrete object in a correct way without knowing
each object specific
type. Can you give some code example how this is done.
Can you give some code example how this can not be done or what your
problem is ?
Given that the topic is called "inheritance and polymorphism" I assume
he is looking for a virtual clone function.
class cloneable
{
public:
virtual cloneable* clone() const = 0;
};
class ABase : public cloneable
{
// whatever stuff here
};
class ADerived : public ABase
{
public:
ADerived * clone() const { return new ADerived( *this ); }
};
class AContainer
{
private:
ABase * itsAPtr;
public:
AContainer( const AContainer& rhs )
: itsAPtr( 0 )
{
try
{
itsAPtr = rhs.itsAPtr->clone();
// anything else
}
catch ( ... )
{
delete itsAPtr;
throw;
}
}
// other stuff
};