Copy Constructor
A copy constructor is a class constructor that can be used to initialize one object with the values of another object of the same class during the declaration statement. In simple words, we can say that, if we have an object called myObject1 and we want to create a new object called myObject2, initialized with the contents of myObject1 then the copy constructor should be used.
Consider the declaration given below:
The declaration (1) declares an object myObject1 of class myClass. The declaration (2) declares another object myObject2 of class myClass as well as initializes it with the contents of existing object myObject1. The copy constructor is, however, defined in the class as a parameterized constructor receiving an object as argument passed by reference.
Consider the example given below,
In the above given class, two constructors have been used; a parameterized and a copy constructor sharing a common class name i.e. address. Thus, constructor can be overloaded. It may be noted that the code for copy constructor has to be written by the programmer. It may be further noted that the argument to a copy constructor has been passed by reference. We can not pass the argument by value because this will result in copy calling itself on and on until the compiler runs out of memory.
Let us now write a program that uses this class to create an object called obj1 with some initial values. It also creates another object called obj2 and copies the contents of obj1 into obj2. It then displays the contents of obj2.
Output:
An object called obj1 of class address is created with some initial values. Another object obj2, a copy of obj1, is created with the help of the copy constructor.
At this stage, a question which arises is tha, this job could have been done by simple assignment of objects i.e. obj1 = obj2, then why to use a copy constructor?
The need of a copy constructor is felt when the class includes pointers which need to be properly initialized. A simple assignment will fail to do this, because both the copies will hold pointers to same memory location.
Comments - No Responses to “Copy Constructor”
Sorry but comments are closed at this time.