Copy Constructors In C++

 
A copy constructors is used to declare and initialize an object from another object. A copy constructoris invoked when you initialize a new object of a class using an existing object.
 
This will happen when:
 
You pass a copy of an object as argument to a function (i.e. when passing by value). When you return an object from a function Or initialize an object during declaration using another object.
 
If we don’t specify a copy constructor, the compiler already has a default copy constructor.
 
This default copy constructor will simply perform a bit-by-bit copy of the original object to the new object (i.e. it will blindly copy everything to the new object).
 
As we saw earlier, this can lead to problems (especially when we use the ‘new’ and ‘delete’ operators in the constructor and destructor of the class).
 
Let us suppose that we are using the ‘new’ operator in the constructor of the class and we have a function whose argument is an object of that class. While calling this function, we will pass an existing object to the function.
 
The function will create a temporary object but it will not invoke the constructor for this new object.
 
Hence the ‘new’ operator (present in the constructor) is not invoked and an exact replica of the passed object is made. During destruction, the temporary object will invoke the destructor (which has the ‘delete’ operator and it will delete the portion of memory allocated to the original object).
 
When the original object is destroyed, it will also invoke the destructor and this will again try to free the same memory. This can lead to serious problems. To solve this problem we have to define our own copy constructor.
 
Let ‘bacteria’ and ‘virus’ be two classes. Each one will have an array called ‘life’ created dynamically using the ‘new’ operator. We shall also define a friend function to which we will pass objects of both ‘bacteria’ and ‘virus’.
 
 
Out put of the program
 
 
Beware: The copy constructor will not work when you use the assignment operator (=) to assign one object to another. In such cases, you have to overload the = operator to avoid the problem (overloading is discussed in the next chapter).
 
Scroll to Top