Cpp Copy Constructor
# C++ Copy Constructor
[ C++ Classes & Objects](#)
A **copy constructor** is a special constructor used to create a new object as a copy of an existing object of the same class. Copy constructors are typically used for:
* Initializing a new object from an existing object of the same type.
* Copying an object to pass it as an argument to a function.
* Copying an object to return it from a function.
If a copy constructor is not defined in a class, the compiler provides one automatically. If a class contains pointers and performs dynamic memory allocation, it must have a copy constructor. The most common form of a copy constructor is:
classname(const classname&obj){// body of constructor}
Here, **obj** is a reference to an object that is used to initialize another object.
## Example
#includeusing namespace std; class Line{public: int getLength(void); Line(int len); // Simple constructor Line(const Line&obj); // Copy constructor ~Line(); // Destructor private: int *ptr; }; // Member function definitions including constructor Line::Line(int len){cout<<"Calling constructor"<<endl; // Allocate memory for pointer ptr = new int; *ptr = len; }Line::Line(const Line&obj){cout<<"Calling copy constructor and allocating memory for pointer ptr"<<endl; ptr = new int; *ptr = *obj.ptr; // Copy the value}Line::~Line(void){cout<<"Freeing memory"<<endl; delete ptr; }int Line::getLength(void){return *ptr; }void display(Line obj){cout<<"line size : "<<obj.getLength()<<endl; }//
YouTip