Connecting Tech Pros Worldwide Forums | Help | Site Map

copy ctor vs default ctor

Newbie
 
Join Date: Aug 2007
Posts: 1
#1: Aug 16 '07
If we do not provide any ctor for a class, the compiler provides the default ctor and copy ctor if needed.

Consider a class Test.
Suppose we provide some ctor in class Test but do not provide the default ctor.

Suppose we try to create
Test obj;

Here the default ctor is needed and the compiler does not provide the default ctor but generates a compilation error.

However if we provide some ctor but do not provide the copy ctor, the compiler does not generate error but provides the copy ctor if needed.

Why doesn't the compiler give error for the absence of copy ctor similar to error for the absence of default ctor.

Kindly explain

Thanks
V.Subramanian
India

Ganon11's Avatar
Moderator
 
Join Date: Oct 2006
Location: New York, United States of America
Posts: 3,428
#2: Aug 16 '07

re: copy ctor vs default ctor


A copy constructor is always included in the class. The default copy constructor copies each value from the source object to the target object - ints, chars, etc. etc. are all copied. This can be a problem when dealing with pointers, as the source object and the target object now have pointers pointing to the same place in memory.

This is where you should include your own copy constructor to avoid this 'shallow copy'. The reason your compiler does not complain is because there is indeed a copy constructor available - the basic one.
Reply