jimjim said:
Hello all,
What other reason is there for using the copy constructor apart from
copying data members which are pointers to dynamically allocated objects?
The sole purpose of a copy constructor is to initialize a
newly created object with a copy of the value of another,
already existing object of the same type. If you don't define
one, the compiler will synthesize one for you (which might or
might not do what is needed). So there's no way to 'not use'
a copy constructor. (One might want to prohibit copying;
this is done by making the copy ctor private, but it's
still there (at least semantically; an optimizer might elude
the code if possible, but the program is still required to
behave 'as if' the code were there.)
In the cases where default copy constructor's behavior
(memberwise assignment) is inappropriate, one must write
a custom copy constructor. Your example of a 'deep copy'
is very common, but not the only reason for writing one.
Other examples include anything which cannot be done with
memberwise assignment. The list is theoretically unlimited,
including 'perverse' things that make the operation not really
a 'copy', but probably the most common general theme is 'resource
acquisition and disposition'. Look up Stroustroup's acronym
"RAII" (Resource Acquisition is Initialization).
-Mike