I wanted to know Why compiler provides default copy constructor..Whats the strategy behind that idea.
Thanks in Advance.
Saving you time? If you have a simple class (ie if you can easily copy construct all its elements) you then don't need to write one.
Because otherwise, when you pass an instance by value, how could the compiler generate one?
From a related (but not same) question - Why don't C++ compilers define operator== and operator!=?:
Stroustrup said this about the default copy constructor in "The Design and Evolution of C++" (Section 11.4.1 - Control of Copying):
I personally consider it unfortunate that copy operations are defined by default and I prohibit copying of objects of many of my classes. However, C++ inherited its default assignment and copy constructors from C, and they are frequently used.
So the answer is that it was included reluctantly by Stroustrup for backwards compatibility with C (probably the cause of most of C++'s warts, but also probably the primary reason for C++'s popularity).
For my own purposes, in my IDE the snippet I use for new classes contains declarations for a private assignment operator and copy constructor so that when I gen up a new class I get no default assignment and copy operations - I have to explicitly remove the declaration of those operations from the private: section if I want the compiler to be able to generate them for me.
If you have a struct
being used by C code, a default copy constructor needs to be there to preserve C struct copying semantics.
Because C++ is not garbage collected, it forces you to keep track of all pointer owners, which is in practice impossible to do, unless you simplify the problem by using lots of copying all over the place so at least you know who owns the copy, and incidentally makes your program slower than a garbage collected one. Auto-generated copy constructors are a nail in the coffin that was put there to hide the gaping hole to hell that is new and delete.
I think you're coming at it from the wrong direction - if the compiler could write a complete and correct 'default' copy constructor for every class or structure, then nobody would complain, would they? The trouble is, the compiler can't do that reliably, so for those cases you need to write your own, overriding the default.