"Alex Vinokur" <al****@go.to> wrote in message
news:44**********************@reader.greatnowhere. com...
If a class contains a member that is a pointer, one should implement copy
constructor.
Should one implement copy constructor if a class contains a member that
is a reference?
It's not really that simple. Just because you have a member which is a
pointer doesn't neccessarily mean you need a copy constructor, but it's a
good indicator.
The point of the statement is that, when your class has a pointer memebr, if
an object of that class ever gets copied, the _value_ of the pointer will
get copied (as well as all other member values). This means that the copy
will have a pointer which points to the same location as the pointer in the
object it copied from!
This _may_ not be a problem. BUT... imagine that this copy is made, and
then the original object is destroyed, and imagine also that your destructor
calls delete on that member pointer. The copy now holds a pointer which is
invalid, because what it pointed to was deleted. So, in this case, you
might want a copy constructor which creates a new object for that pointer to
point to (most likely by using a copy of the pointed-to object).
Look up the "Rule of three" for more information. (Google is a great
source.) I'm pretty sure this is also in the FAQ for this newsgroup
(
http://www.parashift.com/c++-faq-lite).
-Howard