Re: Pointers, auto-pointers, etc.
Ulrich Eckhardt wrote:
[improve this]
struct base
{
virtual ~base() {}
virtual base* clone() const = 0;
};
struct derived1: base
{
virtual derived1* clone() const
{ return new derived1(*this); }
};
struct derived2: base
{
virtual derived2* clone() const
{ return new derived2(*this); }
};
struct base
{
virtual ~base() {}
auto_ptr<base> clone() const
{
auto_ptr<base> res(do_clone());
assert(res.get());
assert(typeid(*this)==typeid(*res));
return res;
}
private:
virtual base* do_clone() const = 0;
};
struct derived1: base
{
auto_ptr<derived1> clone() const
{
auto_ptr<derived1> res(do_clone());
assert(res.get());
assert(typeid(*this)==typeid(*res));
return res;
}
private:
virtual derived1* do_clone() const
{ return new derived1(*this); }
};
The important point here is that the job applicant sees that a covariant
return type can not be translated into a similar auto_ptr type. This then
calls for the typical separation between public, nonvirtual and private,
virtual.
Further, I enforce parts of the implementation of the derived class by
checking that the pointer is non-null and that it points to the right type.
That way you can neither implement it with 'return 0;' nor could you forget
to overload it in a class that derives from another concrete one (even
though that itself is bad design).
Lastly, and there I prefer this one to Lance's, I simply overloaded the
clone() function in the derived class. This is more to write than his
version, but when using it it is less to write. My assumption is simply
that you use the code more often than that you write it.
Now I only wish there was a std::auto_ref that documents that the returned
pointer is never null...
cheers
Uli
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]