Re: Virtual constructor?
kanze wrote:
template< typename Derived, typename Base >
class Clonable : public Base
{
public:
Derived* clone() const
{
return new Derived(
*dynamic_cast< Derived const* >( this ) ) ;
}
private:
virtual Base* doClone() const
{
return clone() ;
}
} ;
template< typename Base >
class AbstractClonable
{
public:
AbstractClonable* clone() const
{
Base* result = doClone() ;
assert( typeid( result ) == typeid( *this ) ) ;
return result ;
}
private:
virtual Base* doClone() const = 0 ;
} ;
Hi James,
I actually find your code quite useful. However, I do find an issue,
when the class hierarchy is as follows:
class A : public public AbstractClonable<A> {};
class B : public Clonable<B, A> {};
class C : public Clonable<C, A> {}'
B* p = new C();
Then p->clone() will really return a B object instead of C.
The solutions I find so far are:
1) Declare only leaf-node objects can be instantiated and let B inherit
from A instead of Clonable<B, A>;
2) Change Clonable::clone() to this effect:
Derived* clone() const
{
if (typeid(Derived) == typeid(*this))
return new Derived(*static_cast<const Derived*>(this));
else
return static_cast<Derived*>(doClone());
}
Any comments? Any better solutions? Anyone knows about the overhead of
typeid?
Best regards,
Yongwei
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]