Copy constructor

  • Thread starter Christian Christmann
  • Start date
C

Christian Christmann

Hi,

I want to clarify that I use the copy constructor correctly.

firstclass.h:

class FirstClass
{
public:
FirstClass();
FirstClass( const FirstClass & );
[...]

private:
SecondClass *mClass;
[...]
};


firstclass.cpp:

FirstClass::FirstClass()
: mClass(NULL)
{
}

FirstClass::FirstClass( const FirstClass &copy )
{
mClass = new SecondClass (*copy.mClass);
// I am not the author of the class SecondClass but I assume
// that its copy constructor is working fine
}
[...]


Is the copy constructor for FirstClass correct?
I want to assure that the private member mClass of the new (copied)
FirstClass object is pointing to a copy of the class member copy.mClass
and avoid both FirstClass objects pointing to the same copy of mClass.

Chris
 
?

=?iso-8859-1?q?Stephan_Br=F6nnimann?=

No, the copy constructor is not correct:
If `copy' is default constructed, the you dereference a 0-pointer,
which is undefined behaviour. You'll need to protect against this.
BTW: don't forget the destructor and assignment operator
(protected against self-assignment).

regards, Stephan Brönnimann
(e-mail address removed)
Open source rating and billing engine for communication networks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,129
Latest member
FastBurnketo
Top