When a new object is generated from an existing object as a copy of the existing object, the copy function Object () { [native code] } is named. When a previously initialized object is given a new value from another object, the assignment operator is used. Function Object () { [native code] } is a member function that uses another object of the same class to initialize an object. The following is a general function prototype for a copy function Object () { [native code] }:

Syntax:

Classname(const classname &obj);

Input:

#include<iostream>

using namespace std; 

class Point

{

private:

     int a, b;

public:co

     Point(int x1, int y1) { a =x1; b = y1; } 

     // Copy constructor

     Point(const Point &p1) {a = p1.a; b = p1.b; } 

     int getX()            { return a; }

     int getY()            { return b; }

};

int main()

{

     Point p1(10, 15); // Normal constructor is called here

     Point p2 = p1; // Copy constructor is called here

     // Let us access values assigned by constructors

     cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

     cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();

     return 0;

}

Output:

C_Plus_Plus_Copy_Constructor_2 

When is a User-Defined Copy Constructor Needed?

According to C++ copy constructor the C++ compiler produces a default copy constructor Object() { [native code] } for each class if it doesn’t define own copy constructor Object() { [native code] }, which performs a member-wise copy between items. In general, the copy function Object() { [native code] } generated by the compiler works well. It just needs to define its own copy function Object() [native code] if an object has pointers or any runtime resource allocation, such as a file handle or a network connection.

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

Copy Constructor vs Assignment Operator

When a new object is generated from an existing object as a copy of the existing object, the copy function Object() { [native code] } is named. When an already initialized object is given a new value from another object, the assignment operator is used.

Myclass c1,c2;

Myclass c3;

 c2=c1;

The above line illustrates the copy constructor

Where Copy Constructor is Needed:

Input:

#include<iostream>

#include<cstring>

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

};

 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("Welcome");

     String str2 = str1;

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

     str2.print();

     str2.change("Welcome you all"); 

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

     str2.print();

     return 0;

Output:

C_Plus_Plus_Copy_Constructor_4. 

What Happens if We Remove the Copy Constructor from the Above Code?

In  c++ copy constructor users don't get the predicted result if we delete the copy function Object() { [native code] } from the above program. Changes to str2 are reflected in str1 as well, which is unexpected.

Input:

#include<iostream>

#include<cstring>

using namespace std; 

class String

{

private:

         char *s;

         int size;

public:

String(const char *str = NULL); // constructor

         ~String() { delete [] s;  }// destructor

         void print() { cout << s << endl; }

         void change(const char *);  // Function to change

}; 

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);

int main()

{

         String str1("Welcome");

         String str2 = str1; 

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

str2.print(); 

str2.change("Welcome you all"); 

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

str2.print();

return 0;

}

Output:

C_Plus_Plus_Copy_Constructor_6  

How to Make the Copy Constructor Private?

According to the C + + copy constructor it is possible to make a copy function Object() { [native code] }. When a copy function Object() { [native code] } in a class is made private, objects in that class become non-copyable. This is especially useful when the class contains pointers or resources that are dynamically allocated. In such cases, it can either write our own copy function Object() { [native code] }, as in the String example above, or create a private copy function Object() { [native code] }, in which case users will receive compiler errors rather than warnings.

Why Does an Argument to a Copy Constructor Must be Passed as a Reference?

According to C + + copy constructor, when an object is transferred by value, a copy function Object() { [native code] } is named. The copy function Object() { [native code] } is a function in and of itself. If an argument is passed by value in a copy function Object() { [native code] }, a call to copy function Object() { [native code] } is made to call copy function Object() { [native code] }, resulting in a non-terminating sequence of calls. As a result, the compiler won't let you move parameters by value.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Why Should the Copy Constructor Argument be Const in C++?

According to C++ copy constructor, we pass an object by reference to the copy function Object() { [native code] }, and we usually pass it as a const reference. One justification for passing a const reference is that it can use const wherever possible in C++ to avoid unintentionally changing objects. This is one compelling excuse to transfer references as const, but there are others.

Input:

#include<iostream>

using namespace std; 

class Test

{

/* Class data members */

public:

Test(Test &t) { /* Copy data members from t*/}

Test()  { /* Initialize data members */ }

}; 

Test fun()

{

     cout << "fun() Called\n";

     Test t;

     return t;

int main()

{

     Test t1;

     Test t2 = fun();

     return 0;

}

Output:

C_Plus_Plus_Copy_Constructor_8

Need to change the copy constructor by the following:

Test(const Test &t) { cout << "Copy Constructor Called\n"; }

The fun() function returns a value. As a result, the compiler generates a temporary entity, which is then copied to t2 using the original program's copy function Object() { [native code] } (The temporary object is passed as an argument to the copy constructor). The compiler error occurs because compiler-created temporary objects cannot be bound to non-const references, despite the fact that the original program attempts to do so. It doesn't make sense to change something that isn't broken.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

According to C++ copy constructor, when an object is made, a function Object() { [native code] } is a special type of member function that is called automatically. A function Object() { [native code] } in C++ has the same name as the class it belongs to, and it does not have a return form.

In this article you learned about stack, implementation, operations with syntax and examples. To get expertise in C++ programming you can join Simplilearn’s C++ certification training course. For learners, Simplilearn has made a special selection of courses available for free. Join Simplilearn’s free courses and revolutionise your profession with certificates, specialisations, and dozens of other courses.

Have any questions for us? Leave them in the comments section of this article, and our experts will get back to you on them, as soon as possible!