What is Copy Constructor in C++: Definition and Example
copy constructor in C++ is a special constructor used to create a new object as a copy of an existing object. It takes a reference to an object of the same class and duplicates its values to the new object.How It Works
Imagine you have a recipe card and you want to make a copy of it to share with a friend. The copy constructor works like making that exact copy of the recipe card. When you create a new object from an existing one, the copy constructor duplicates all the data from the original object to the new one.
In C++, if you don't write a copy constructor, the compiler creates a default one that copies each member variable one by one. But sometimes you want to control how copying happens, especially if your object manages resources like memory or files. Then you write your own copy constructor to make sure the copy is done safely and correctly.
Example
This example shows a class with a copy constructor that copies the value of a member variable from one object to another.
#include <iostream> using namespace std; class Box { public: int length; // Constructor Box(int l) : length(l) {} // Copy constructor Box(const Box &b) { length = b.length; cout << "Copy constructor called!" << endl; } void showLength() { cout << "Length: " << length << endl; } }; int main() { Box box1(10); // Normal constructor Box box2 = box1; // Copy constructor called box1.showLength(); box2.showLength(); return 0; }
When to Use
Use a copy constructor when you want to create a new object that is a copy of an existing object. This is common when passing objects by value to functions or returning objects from functions.
It is especially important when your class manages resources like dynamic memory, file handles, or network connections. Writing a custom copy constructor helps avoid problems like double freeing memory or sharing resources unintentionally.
For example, if you have a class that holds a pointer to a dynamic array, the default copy constructor would copy the pointer address only, causing both objects to share the same array. A custom copy constructor can create a new array and copy the contents, making the objects independent.
Key Points
- A copy constructor creates a new object by copying an existing one.
- It takes a reference to an object of the same class as a parameter.
- The compiler provides a default copy constructor if you don't write one.
- Write your own copy constructor when your class manages resources to avoid shallow copy issues.
- Copy constructors are called when passing or returning objects by value.