Re: Bewildering of polymorhpical class
wij@seed.net.tw wrote:
The copy constructors of B and D are endless self-recursive.
How should the copy constructor and the member clone be defined
for such polymorphical classes containing B* member?
class B {
B *_pb;
public:
B(const B& src) : _pb(new B(src)) {};
virtual ~B() { delete _pb; _pb=NULL; };
virtual B* clone(void) { return new B(*this); };
};
class D : public B {
B *_pb;
public:
D(const D& src) : B(src), _pb(new D(src)) {};
virtual ~D() { delete _pb; _pb=NULL; };
virtual D* clone(void) { return new D(*this); };
};
One thing up front, which is not really related to your problem, is that
there are two small problems here:
1. clone should be const - of course it should be applicable to a const
object.
2. There is no need for the ';' after the curlies of a memberfunction. This
is correct syntax according to C++ though, but not required - I consider it
ugly and an oversight in the standard.
Secondly, there are two pointers of type B* in every D, one is B::_pb the
other is D::_pb. I don't think you want that. Now, how you clone a B or a D
depends on how these are composed. As said, I don't think your code
resembles what you really want to express. Rather, I think you only want
one pointer in both instances.
Now, assuming you have only one pointer to a B, cloning such an object is
done in two steps:
1. You clone the object inself. This means leaving the pointer empty at
first.
2 Then, if the original's pointer is not null cloning that object, too.
Yes, this recurses, but it doesn't recurse infinitely unless there is a
loop - this however would be a mistake anyway because each pointer marks
ownership (according to the dtor) and an object that owns another object
which own the first object is plainly a programming error. BTW:
std::auto_ptr is made for holding ownership and would be perfect for this
case to make things exception-safe. It would also mean less code to write
yourself.
HTH
Uli
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]