Copy Constructor in C++

In this tutorial, we will learn about the copy constructor in C++.

We already know that a constructor is a special member function of a class. The task of a constructor is to initialize the objects of its class.

A constructor is responsible for constructing the values of data members of a class.

Copy Constructor

A copy constructor is a special type of constructor that can accept a reference to its class as a parameter. Therefore, a copy constructor can declare and initialize an object from another object.

The process of assigning values to an object by the help of copy constructor is known as copy initialization. If no copy constructor is explicitly defined, the compiler supplies its copy constructor.

How a copy constructor works in C++

The sample code given below will help you understand the working of a copy constructor:

#include<iostream>
using namespace std;
class emp
{
   private:
       int age;
       int salary;
   public:
       emp(int a,int s)
       {
           age=a;
           salary=s;
       }
    emp(emp &e)
    {
        age=e.age;
        salary=e.salary;
    }
    int showage()
    {
        return age;
    }
    int showsal()
    {
        return salary;
    }
};
int main()
{
    emp E1(45,100000); //normal constructor is called
    emp  E2(E1); //copy constructor is called
    cout<<"age of E2= "<<E2.showage()<<endl; //values are copied into E2
    cout<<"salary of E2= "<<E2.showsal()<<endl;
    return 0;
}

The output will look like this:

age of E2= 45
salary of E2= 100000

Process returned 0 (0x0)   execution time : 0.016 s
Press any key to continue.

In the above example, we have initialized the values of age and salary of an employee E1 using a regular parameterized constructor. Following this, the copy constructor is called with the statement

emp E2(E1);

So, the values of age and salary of E1 are now copied into E2. Thus, we have initialized an object with an already existing object. The below-given statement is also valid in this context:

emp E2=E1;

Note that this is not an assignment operation. When a ‘=’ sign is placed during the initialization of an object using another, the constructor is invoked. But the statement

emp E2;
E2=E1;

is a normal assignment statement. The key difference between the two methods described above is that when we initialize an object with another, the first object(E1) retains its values while copying the same values into another object(E2).

While in the second statement, the values of E1 are assigned to E2, so that E1 no longer holds its initial values.

It is important to note that a reference variable has been used as an argument to the copy constructor. We cannot pass the argument by value.

With this, we come to the end of this tutorial. Hope it was helpful.

Also Read:

this Pointer in C++

Leave a Reply

Your email address will not be published. Required fields are marked *