Doug
Tue May 29 11:04:09 CDT 2007
On Tue, 29 May 2007 17:37:21 +0200, Anders Eriksson <andis59@gmail.com>
wrote:
>Hello,
>
>I have a class that has a pointer to another class as a private member
>variable. I now want to create a copy constructor for this class and I
>don't get it.
>
>class myClass
>{
> int m_x;
> yourClass * m_yObj;
>
> myClass(myClass* mobj);
>};
>
>myClass::myClass(myClass* mobj)
>{
> m_x = mobj->m_x;
> m_yObj = ?????
>}
That is not a copy ctor. A copy ctor uses a (usually const) reference
parameter, not a pointer:
myClass::myClass(const myClass& mobj)
>How do I create a deep copy of the m_yObj object? I want new object with
>the same values
Assuming yourClass implements a copy ctor:
myClass::myClass(const myClass& mobj)
: m_x(mobj.m_x),
m_yObj(new yourClass(*mobj.m_yObj))
{
}
It doesn't matter here, but it's a good habit to use the member
initialization list when possible. Note that since you own a dynamically
allocated object and are storing it in a plain old pointer, you have to
implement a destructor and assignment operator as well. Using std::auto_ptr
would relieve you from writing the dtor, but it's still critical to write
the assignment operator; see this page for how to make it exception-safe:
http://www.gotw.ca/gotw/059.htm
You also might want to check out the smart pointer classes at boost.org.
--
Doug Harrison
Visual C++ MVP