Home >>C++ Tutorial >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++.
There are generally two types of the copy constructor in C++:
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; }
These are the following scenarios when a copy constructor is called:
There are generally two types of the copies that are produced by the constructor:
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.