C++ Programming Concepts - Why is Copy Constructor required?
When it comes to C++ Programming concepts, Copy Constructor is a very important and quite complex one, due to different dimensions of understanding required. One dimension is the syntax of the copy constructor which includes a reference to the object required - why is this reference compulsory?
Another dimension includes the question - when is the copy constructor invoked, and when it is the assignment operator's turn to be in action?
But first and foremost, it's important to understand, what a copy constructor does, and why is the copy constructor required in first place?
The copy constructor is a type of constructor, handling the special cases when a new object is to be created using the copy of an old object of the same class. For instance, if you have an existing square object with specific values of co-ordinates in a two dimensional space, and you want to create a new square object with same values for co-ordinates, you can create a copy of the old object using a copy constructor.
But why a copy constructor? After all, we could as well get the values of all the co-ordinates using the getter function, and create a new object with default initial values, after which we could assign the values that we got from the old square object using the setter function. Do you see the overhead already? It's quite similar to the overhead we talked about in the Need for the constructor.
While we can definitely follow the above steps and create the new object, there is a significant overhead involved. Assuming that the class has about four two dimensional co-ordinate data members - each an object of Point class, we will end up calling first the constructor of the Point Class four times - which will initialize the four Point objects with default initial values, say (0,0); and then we would be invoking the setter function four times. Don't forget the call to the getter function of Square class (if there exists one) to retrieve the values of co-ordinates of the old Square object.
Contrast the above situation with this one: You have a copy constructor for both Square and Point classes, thus you simply provide the old object, and the copy constructor initializes the values with the values of the member of the old object.
However, the scenario that we talked about above, is a very simple scenario where copy construction is just bitwise copy from old integer co-ordinate members to new ones - and for such cases the copy constructor provided by the compiler by default is enough, you don't need to write one. But, there can exist more complicated scenarios where you would want your copy constructor to manage resources for e.g., a dynamic copy constructor, which we will discuss later.