Re: Copy constructor question.
Vinesh S <vinesh2681@gmail.com> wrote in news:a9600cbb-6650-420d-a2f9-
ee04abbf4f5b@i9g2000yqe.googlegroups.com:
Hello All,
i have a question with copy construction here.
i have for example
class A // abstract base class
{
...
}
class B : public A
{
...
}
class C : public A
{
...
}
also i have totally an unrelated class called D.
class D
{
D(A* basepointer , int k, int y) // constructor
{
....
basePtr = basePointer;
}
private
A* basePtr
}
QUESTION:
how do i write a copy constructor for Class D?
1. problem i face is : if am not allowed to use memcpy ...
... i need to copy the value pointed by the basePtr in the copy
constructor to the resulting class.
but i dont know what instance it holds ( whether class b or class
c ) to allocate memory and copy it
It depends on if you need to make a deep copy or not. If not, then you
can just copy the A* pointer (the pointed object will then remain in
shared use and care must be taken when accessing and destroying it,
usually some kind of smartpointer should be used to take care at least of
the latter).
If you need deep copy, then the standard way is to define a pure virtual
clone() function in the A base class and override it in each non-abstract
derived class, e.g.
virtual A* C::Clone() const {return new C(*this);}
The copy ctor for D would then look like:
D::D(const D& source)
: basePtr(source.basePtr->Clone())
{}
hth
Paavo