inheritance and polymorfism

T

Tony Johansson

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.

//Tony
 
?

=?ISO-8859-1?Q?Stefan_N=E4we?=

Tony said:
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 ?

/S
 
M

msalters

Tony Johansson schreef:
Hello experts!

How is it possible to copy concrete object in a correct way without knowing
each object specific type.

What's your problem? There are at least two solutions, with templates
or
with virtual functions. Or is this homework?

Regards,
Michiel Salters
 
E

Earl Purple

Stefan said:
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
};
 
M

Marc Mutz

Earl said:
try
{
itsAPtr = rhs.itsAPtr->clone();
// anything else
}
catch ( ... )
{
delete itsAPtr;
throw;
}

std::auto_ptr<ABase> tmp( rhs.itsAPtr->clone() );
// anything else
itsAPtr = tmp.release();

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top