Home >>C++ Tutorial >C++ Copy Constructor

C++ Copy Constructor

C++ Copy Constructor

An overloaded constructor that is used to initialize and declare an object from another object is known as a copy constructor in C++.

Types of Copy Constructor

There are generally two types of the copy constructor in C++:

  • Default Copy Constructor : The default copy constructor in C++ is defined by the compiler and the compiler also supplies the constructor if there is no copy constructor defined by the user.
  • User-Defined Constructor : This type of constructor is generally defined by the user or the programmer.

Syntax Of User-defined Copy Constructor

Here is the syntax of the user-defined copy constructor:

Class_name(const class_name &old_object);  

Here is an example of the user-defined copy constructor for your better understanding:

#include<iostream>  
using namespace std;  
class Student  
{  
   public:  
    int x;  
    Student(int a)//This is  parameterized constructor.  
    {  
      x=a;  
    }  
    Student(Student &i) //This is copy constructor  
    {  
        x = i.x;  
    }  
};  
int main()  
{  
  Student stu(10); //Here need to  Call parameterized constructor.  
  Student stu2(stu);//Calling the copy constructor.	
  cout<<stu.x;
  cout<<stu2.x;	
  return 0;  
}
Output :10 10

Copy Constructor is called when

These are the following scenarios when a copy constructor is called:

  • The first case is when a object is initialized by the user with another existing object that is of the same type of class.
  • Whenever the same class type object is generally passed by value generally as an argument then the copy constructor is called.
  • Whenever the same class type object is generally returned by value by the function then the copy constructor is called.

Types of copies produced by the constructor

There are generally two types of the copies that are produced by the constructor:

  • Shallow copy
  • Deep copy

1.Shallow copy

  • The shallow copy can only be produced by the default copy constructor.
  • The procedure of creating the copy of an object just by copying the data of all the member variables exactly the same is known as the shallow copy.

2.Deep Copy

The deep copy in the copy constructor, allocates the memory for the copy dynamically and then the actual value is copied but the source from which the data is copied and the copied data have very distinct memory locations. This ensures that the data copied and the source from where it has been copied shares the distinct memory locations. User-defined constructor should be written by the user in the deep copy.


Popular Tutorials