Connecting Tech Pros Worldwide Help | Site Map

inheritance and polymorfism

Tony Johansson
Guest
 
Posts: n/a
#1: Aug 19 '05
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


msalters
Guest
 
Posts: n/a
#2: Aug 19 '05

re: inheritance and polymorfism



Tony Johansson schreef:
[color=blue]
> Hello experts!
>
> How is it possible to copy concrete object in a correct way without knowing
> each object specific type.[/color]

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

Regards,
Michiel Salters

Stefan Näwe
Guest
 
Posts: n/a
#3: Aug 19 '05

re: inheritance and polymorfism


Tony Johansson wrote:[color=blue]
> 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.[/color]

Can you give some code example how this can not be done or what your
problem is ?

/S
Earl Purple
Guest
 
Posts: n/a
#4: Aug 19 '05

re: inheritance and polymorfism



Stefan Näwe wrote:[color=blue]
> Tony Johansson wrote:[color=green]
> > 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.[/color]
>
> Can you give some code example how this can not be done or what your
> problem is ?
>[/color]

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
};

Marc Mutz
Guest
 
Posts: n/a
#5: Aug 19 '05

re: inheritance and polymorfism


Earl Purple wrote:[color=blue]
> try
> {
> itsAPtr*=*rhs.itsAPtr->clone();
> //*anything*else
> }
> catch*(*...*)
> {
> delete*itsAPtr;
> throw;
> }
>[/color]

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

Marc

Closed Thread