The Wayback Machine - https://web.archive.org/web/20240730090351/https://www.geeksforgeeks.org/copy-constructor-in-cpp/
Open In App

Copy Constructor in C++

Last Updated : 22 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

A copy constructor is a type of constructor that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor.  

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.

Syntax of Copy Constructor in C++

Copy constructor takes a reference to an object of the same class as an argument:

className (const ClassName &obj)
{
member1 = obj.member1;
// for dynamic resources

......
}

Here, the const qualifier is optional but is added so that we do not modify the obj by mistake.

Syntax of Copy Constructor with Example

Syntax of Copy Constructor

Examples of Copy Constructor in C++

Example 1: User Defined Copy Constructor

CPP
// C++ program to illustrate the use of copy constructor
#include <iostream>
#include <string.h>
using namespace std;

// Class definition for 'student'
class student {
    int rno;
    string name;
    double fee;

public:
    // Parameterized constructor
    student(int, string, double);
    // Copy constructor
    student(student& t)
    {
        rno = t.rno;
        name = t.name;
        fee = t.fee;
        cout << "Copy Constructor Called" << endl;
    }
    // Function to display student details
    void display();
};

// Implementation of the parameterized constructor
student::student(int no, string n, double f)
{
    rno = no;
    name = n;
    fee = f;
}

// Implementation of the display function
void student::display()
{
    cout << rno << "\t" << name << "\t" << fee << endl;
}

int main()
{
    // Create student object with parameterized constructor
    student s(1001, "Manjeet", 10000);
    s.display();

    // Create another student object using the copy
    // constructor
    student manjeet(s);
    manjeet.display();

    return 0;
}

Output
1001    Manjeet    10000
Copy Constructor Called
1001    Manjeet    10000

If the programmer does not define the copy constructor, the compiler does it for us.

Example 2: Default Copy Constructor

An implicitly defined copy constructor will copy the bases and members of an object in the same order that a constructor would initialize the bases and members of the object.

C++
// Implicit copy constructor Calling
#include <iostream>
using namespace std;

class Sample {
    int id;

public:
    void init(int x) { id = x; }
    void display() { cout << endl << "ID=" << id; }
};

int main()
{
    Sample obj1;
    obj1.init(10);
    obj1.display();

    // Implicit Copy Constructor Calling
    Sample obj2(obj1); // or obj2=obj1;
    obj2.display();
    return 0;
}

Output
ID=10
ID=10

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


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

Example: Class Where a Copy Constructor is Required

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++
// C++ program to demonstrate the
// Working of Copy constructor
#include <cstring>
#include <iostream>
using namespace std;

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

public:
    String(const char* str = NULL); // constructor
    ~String() { delete[] s; } // destructor
    String(const String&); // copy constructor
    void print()
    {
        cout << s << endl;
    } // Function to print string
    void change(const char*); // Function to change
};

// In this the pointer returns the CHAR ARRAY
// in the same sequence of string object but
// with an additional null pointer '\0'
String::String(const char* str)
{
    size = strlen(str);
    s = new char[size + 1];
    strcpy(s, str);
}

void String::change(const char* str)
{
    delete[] s;
    size = strlen(str);
    s = new char[size + 1];
    strcpy(s, str);
}

String::String(const String& old_str)
{
    size = old_str.size;
    s = new char[size + 1];
    strcpy(s, old_str.s);
}

int main()
{
    String str1("GeeksQuiz");
    String str2 = str1;

    str1.print(); // what is printed ?
    str2.print();

    str2.change("GeeksforGeeks");

    str1.print(); // what is printed now ?
    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 member s 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).

Refer to this article for more details – When is a Copy Constructor Called in C++?

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? 

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.

Frequently Asked Questions in C++ Copy Constructors

Can we make the copy constructor private? 

Yes, a copy constructor can be made private. When we make a copy constructor private in a class, objects of that class become non-copyable. This is particularly useful when our class has pointers or dynamically allocated resources. In such situations, we can either write our own copy constructor like the above String example or make a private copy constructor so that users get compiler errors rather than surprises at runtime.

Why argument to a copy constructor must be passed as a reference? 

If you pass the object by value in the copy constructor, it will result in a recursive call to the copy constructor itself. This happens because passing by value involves making a copy, and making a copy involves calling the copy constructor, leading to an infinite recursion. Using a reference avoids this recursion. So, we use reference of objects to avoid infinite calls.

Why argument to a copy constructor should be const?

One reason for passing const reference is, that we should use const in C++ wherever possible so that objects are not accidentally modified. This is one good reason for passing reference as const, but there is more to it than ‘Why argument to a copy constructor should be const?’

Related Articles:

 



Previous Article
Next Article

Similar Reads

Copy Constructor vs Assignment Operator in C++
Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them: Copy constructor Assignment operator It is called when a new object is created from an existing object, as a copy of the existing objectThis operator is called when an already
2 min read
Advanced C++ | Virtual Copy Constructor
In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it's exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from another existing object. Precisely the copy constructo
5 min read
Why copy constructor argument should be const in C++?
When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified. This is one good reason for passing reference as const, but there is more to it. For example, pr
3 min read
When is a Copy Constructor Called in C++?
A copy constructor is a member function that initializes an object using another object of the same class. The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object. In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value
2 min read
When Should We Write Our Own Copy Constructor in C++?
A copy constructor is a member function that initializes an object using another object of the same class. (See this article for reference). When should we write our own copy constructor?C++ compiler provides a default copy constructor (and assignment operator) with class. When we don't provide an implementation of the copy constructor (and assignm
2 min read
Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()
Various varieties of copy() exist in C++ STL that allows to perform the copy operations in different manners, all of them having their own use. These all are defined in header &lt;algorithm&gt;. This article introduces everyone to these functions for usage in day-to-day programming. 1. copy(strt_iter1, end_iter1, strt_iter2) : The generic copy func
5 min read
Shallow Copy and Deep Copy in C++
In general, creating a copy of an object means to create an exact replica of the object having the same literal value, data type, and resources. There are two ways that are used by C++ compiler to create a copy of objects. Copy ConstructorAssignment Operator// Copy Constructor Geeks Obj1(Obj); or Geeks Obj1 = Obj; // Default assignment operator Gee
6 min read
Does C++ compiler create default constructor when we write our own?
No, the C++ compiler doesn't create a default constructor when we initialize our own, the compiler by default creates a default constructor for every class; But, if we define our own constructor, the compiler doesn't create the default constructor. This is so because the default constructor does not take any argument and if two default constructors
1 min read
What is conversion constructor in C++?
Pre-requisite: Type Conversion in C++ and Use of explicit keyword in C++ A conversion constructor is a single-parameter constructor that is declared without the function specifier explicitly. The compiler uses conversion constructors to convert objects from the type of the first parameter to the type of the conversion constructor's class. Example:
3 min read
Passing a vector to constructor in C++
When class member is a vector object (not a reference).We can simply assign in constructor. C/C++ Code // Passing vector object to a constructor. #include &amp;lt;iostream&amp;gt; #include &amp;lt;vector&amp;gt; using namespace std; class MyClass { vector&amp;lt;int&amp;gt; vec; public: MyClass(vector&amp;lt;int&amp;gt; v) { vec = v; } void print()
2 min read
Practice Tags :
three90RightbarBannerImg