Open In App

Copy Constructor in C++

Last Updated : 19 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A copy constructor is a type of constructor that creates an object using another object of the same class. The process of initializing members of an object through a copy constructor is known as copy initialization. It is also called member-wise initialization because the copy constructor initializes one object with the existing object, both belonging to the same class on a member-by-member copy basis.

Example:

C++
#include <iostream>
using namespace std;

// Create a demo class
class A {
public:
    int x;
};

int main() {
  
  	// Creating an a1 object
    A a1;
    a1.x = 10;
    cout << "a1's x = " << a1.x << endl;

    // Creating another object using a1
  	// Copy Constructor Calling
    A a2(a1);
    cout << "a2's x = " << a2.x;

    return 0;
}

Output
a1's x = 10
a2's x = 10

Explanation: In this example, we were able to construct a2 object using already created object a1. But wait a minute, we haven't defined any copy constructor here, so why we were able to create an object using already existing object of same class? Actually, C++ compiler by default creates a simple copy constructor when it is not explicitly defined by the programmer. It is called implicit copy constructor, and it will copy the bases and members of an object in the same order that they were present in the code.

User Defined Copy Constructor

C++ also allows programmers to create their own version of copy constructor known as user defined or explicit copy constructor.

C++
className (const ClassName &obj) {
    // Body of copy constructor
}

Here, the const is optional but is added so that we do not modify the obj by mistake. Copy constructor takes a reference to an object of the same class as an argument.

Syntax of Copy Constructor with Example
Syntax of Copy Constructor

Example:

CPP
#include <iostream>
using namespace std;

class A {
public:
    int x;
    A(){};
  
  	// Copy Constructor definition
    A (A& obj) {
        x = obj.x;
      	cout << "Copy constructor "
      	        "called" << endl;
    }
};

int main() {
  
  	// Creating an object of
  	// class A
    A obj1;
    obj1.x = 10;
    cout << "obj1's x = " << obj1.x << endl;

    // Creating another object by
    // copying already created object
    A obj2(obj1);
    cout << "obj2's x = " << obj2.x;
    return 0;
}

Output
obj1's x = 10
Copy constructor called
obj2's x = 10

Note: If we define a copy constructor, then implicit definition of the default constructor will not be provided by the compiler. So, we would have to manually define it too.

Need of User Defined Copy Constructor

If we don't define our own copy constructor, the C++ compiler creates a default copy constructor for each class which works fine in general. However, we need to define our own copy constructor only if an object has pointers or any runtime allocation of the resource like a file handle, a network connection, etc because the default constructor does only shallow copy.

Shallow Copy means that only the pointers will be copied not the actual resources that the pointers are pointing to. This can lead to dangling pointers if the original object is deleted.

shallow-copy-concept-in-cpp
Shallow Copy

Deep copy is possible only with a user-defined copy constructor. In a user-defined copy constructor, we make sure that pointers (or references) of copied objects point to new copy of the dynamic resource allocated manually in the copy constructor using new operators.

deep-copy-concept-in-cpp
Deep Copy

Following is a complete C++ program to demonstrate the use of the Copy constructor. In the following String class, we must write a copy constructor. 

C++
#include <bits/stdc++.h>
using namespace std;

class String {
private:
    char* s;
    int size;

public:
    String(const char* str){
        size = strlen(str);
        s = new char[size + 1];
        strcpy(s, str);
    }
    ~String() { delete[] s; }
  
  	 // Copy constructor
    String(const String& old_str){
        size = old_str.size;
        s = new char[size + 1];
        strcpy(s, old_str.s);
    }
    void print() {
        cout << s << endl;
    }
    
    void change(const char* str){
        delete[] s;
        size = strlen(str);
        s = new char[size + 1];
        strcpy(s, str);
    }
};

int main() {
    String str1("GeeksQuiz");
  
  	// Create str2 from str1
    String str2 = str1;
    str1.print();
    str2.print();

    // Update the str2 object
    str2.change("GeeksforGeeks");

    str1.print();
    str2.print();
    return 0;
}

Output
GeeksQuiz
GeeksQuiz
GeeksQuiz
GeeksforGeeks

Note: Such classes also need the overloaded assignment operator. See this article for more info - C++ Assignment Operator Overloading

What would be the problem if we remove the copy constructor from the above code?

If we remove the copy constructor from the above program, we don't get the expected output. The changes made to str2 reflect in str1 as well which is never expected. Also, if the str1 is destroyed, the str2's data members will be pointing to the deallocated memory.

When is the Copy Constructor Called?

In C++, a copy constructor may be called in the following cases

  • When an object of the class is returned by value.
  • When an object of the class is passed (to a function) by value as an argument.
  • When an object is constructed based on another object of the same class.
  • When the compiler generates a temporary object.

It is, however, not guaranteed that a copy constructor will be called in all these cases, because the C++ Standard allows the compiler to optimize the copy away in certain cases, one example is the return value optimization (sometimes referred to as RVO).

Copy Elision

In copy elision, the compiler prevents the making of extra copies by making the use to techniques such as NRVO and RVO which results in saving space and better the program complexity (both time and space); Hence making the code more optimized.

Copy Constructor vs Assignment Operator

The main difference between Copy Constructor and Assignment Operator is that the Copy constructor makes a new memory storage every time it is called while the assignment operator does not make new memory storage.

Which of the following two statements calls the copy constructor and which one calls the assignment operator?

C++
MyClass t1, t2;
MyClass t3 = t1;  // ----> (1)
t2 = t1;          // -----> (2) 

A copy constructor is called when a new object is created from an existing object, as a copy of the existing object. The assignment operator is called when an already initialized object is assigned a new value from another existing object. In the above example (1) calls the copy constructor and (2) calls the assignment operator.


Next Article
Practice Tags :

Similar Reads