Copy Constructor in C++ - GeeksforGeeks (2023)

Pre-requisite: Constructor in C++

A copy constructor is a member function 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.

Example:

Copy Constructor in C++ - GeeksforGeeks (1)

Syntax of Copy Constructor

Characteristics of Copy Constructor

1. The copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object.

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

Sample(Sample &t){ id=t.id;}

3. The process of initializing members of an object through a copy constructor is known as copy initialization.

4. 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.

5. The copy constructor can be defined explicitly by the programmer. If the programmer does not define the copy constructor, the compiler does it for us.

Example:

C++

// C++ program to demonstrate the working

// of a COPY CONSTRUCTOR

#include <iostream>

using namespace std;

class Point {

private:

int x, y;

public:

Point(int x1, int y1)

{

x = x1;

y = y1;

}

// Copy constructor

Point(const Point& p1)

{

x = p1.x;

y = p1.y;

}

int getX() { return x; }

int getY() { return y; }

};

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

p1.x = 10, p1.y = 15p2.x = 10, p2.y = 15

Types of Copy Constructors

1. 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

(Video) Copy Constructor in C++ | C++ Tutorials for Beginners #34

#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=10ID=10

2. User Defined Copy Constructor

A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references, such as to a file, in which case a destructor and an assignment operator should also be written

C++

// Explicitly copy constructor Calling

#include<iostream>

using namespace std;

class Sample

{

int id;

public:

void init(int x)

{

id=x;

}

Sample(){} //default constructor with empty body

Sample(Sample &t) //copy constructor

{

id=t.id;

}

void display()

{

cout<<endl<<"ID="<<id;

}

};

int main()

{

Sample obj1;

obj1.init(10);

obj1.display();

Sample obj2(obj1); //or obj2=obj1; copy constructor called

obj2.display();

return 0;

}

Output

ID=10ID=10

C++

(Video) 94. Copy Constructor in C++ (Hindi)

// C++ Programt to demonstrate the student details

#include <iostream>

#include <string.h>

using namespace std;

class student {

int rno;

string name;

double fee;

public:

student(int, string, double);

student(student& t) // copy constructor

{

rno = t.rno;

name = t.name;

fee = t.fee;

}

void display();

};

student::student(int no, string n, double f)

{

rno = no;

name = n;

fee = f;

}

void student::display()

{

cout << endl << rno << "\t" << name << "\t" << fee;

}

int main()

{

student s(1001, "Ram", 10000);

s.display();

student ram(s); // copy constructor called

ram.display();

return 0;

}

Output

1001 Ram 100001001 Ram 10000

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 which results in saving space and better the program complexity(both time and space); Hence making the code more optimized.

Example:

C++

// C++ program to demonstrate

// the working of copy elision

#include <iostream>

using namespace std;

class GFG {

public:

void print() { cout << " GFG!"; }

};

int main()

{

GFG G;

(Video) Copy Constructor in C++ | C++ Programming | In Hindi

for (int i = 0; i <= 2; i++) {

G.print();

cout<<"\n";

}

return 0;

}

Output

 GFG! GFG! GFG!

Now it is on the compiler to decide what it wants to print, it could either print the above output or it could print case 1 or case 2 below, and this is what Return Value Optimization is. In simple words, RVO is a technique that gives the compiler some additional power to terminate the temporary object created which results in changing the observable behavior/characteristics of the final program.

Case 1:

GFG!GFG!

Case 2:

GFG!

When is a user-defined copy constructor needed?

If we don’t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which does a member-wise copy between objects. The compiler-created copy constructor works fine in general. 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.

The default constructor does only shallow copy.

Copy Constructor in C++ - GeeksforGeeks (2)

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 memory locations.

Copy Constructor in C++ - GeeksforGeeks (3)

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. See this for more details.

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.

Example:

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

(Video) Copy Constructor in C++ | C++ Tutorial | Mr. Kishore

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

GeeksQuizGeeksQuizGeeksQuizGeeksforGeeks

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.

C++

#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

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

}

// In this the pointer returns the CHAR ARRAY

// in the same sequence of string object but

// with an additional null pointer '\0'

void String::change(const char* str) { strcpy(s, str); }

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:

GeeksQuizGeeksQuizGeeksforGeeksGeeksforGeeks

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?

A copy constructor is called when an object is passed by value. Copy constructor itself is a function. So if we pass an argument by value in a copy constructor, a call to the copy constructor would be made to call the copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn’t allow parameters to be passed by value.

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?’

This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write your article at write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


My Personal Notesarrow_drop_up

(Video) Copy Constructor in C++(Hindi) | Syntax and Example of Copy Constructor in C++

FAQs

Is copy constructor necessary in C++? ›

A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references, such as to a file, in which case a destructor and an assignment operator should also be written (see Rule of three).

How many arguments can be passed copy constructor? ›

A copy constructor always takes one parameter, reference to the type for which it belongs, there maybe other parameters but they must have default values.

What is the problem of copy constructor? ›

But the problem with the default copy constructor (and assignment operator) is: When we have members which dynamically get initialized at run time, the default copy constructor copies this member with the address of dynamically allocated memory and not a real copy of this memory.

What is a copy constructor in C++ list out the needs of creating a copy constructor by writing a copy constructor for a university class in C++? ›

What is a Copy Constructor in C++? Copy constructors are the member functions of a class that initialize the data members of the class using another object of the same class. It copies the values of the data variables of one object of a class to the data members of another object of the same class.

What happens when a programmer doesn't define any copy constructor? ›

Default copy constructor: The compiler automatically generates a default copy constructor if the programmer does not provide one. The default copy constructor performs a member-wise copy of the object, meaning that it copies the values of all the data members of the object to the new object.

Why are copy constructors useful? ›

Copy Constructor is used to create and exact copy of an object with the same values of an existing object.

Can copy constructor be overloaded? ›

A Copy constructor is an overloaded constructor used to declare and initialize an object from another object.

How many times copy constructor will be invoked? ›

You call the function by value and do two copies inside.

Can you have multiple copy constructors C++? ›

A class can have multiple copy constructors, e.g. both T::T(const T&) and T::T(T&). If some user-defined copy constructors are present, the user may still force the generation of the implicitly declared copy constructor with the keyword default .

Why do we delete the copy constructor? ›

When to delete copy constructor and assignment operator? Copy constructor (and assignment) should be defined when ever the implicitly generated one violates any class invariant. It should be defined as deleted when it cannot be written in a way that wouldn't have undesirable or surprising behaviour.

What is the disadvantages of constructor in C++? ›

In a default constructor, every object in the class is initialized to the same set of values. It is not possible to initialize different objects with different initial values. This is one of the disadvantages of a default constructor.

Why do you have to pass the argument to a copy constructor? ›

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.

What is the difference between parameterized and copy constructor? ›

In C#, the copy constructor is also a parameterized constructor. A parameterized constructor is a constructor that contains a parameter of the same class type. The copy constructor is useful whenever we want to initialize a new instance to an existing instance's values.

What is the difference between copy constructor and clone? ›

Copy Constructor vs.

However, the copy constructor has some advantages over the clone method: The copy constructor is much easier to implement. We do not need to implement the Cloneable interface and handle CloneNotSupportedException. The clone method returns a general Object reference.

Does C++ automatically create a copy constructor? ›

In C++, the compiler automatically generates the default constructor, copy constructor, copy-assignment operator, and destructor for a type if it does not declare its own. These functions are known as the special member functions, and they are what make simple user-defined types in C++ behave like structures do in C.

Why can not we pass an object by value to a copy constructor? ›

Passing by value (rather than by reference) means a copy needs to be made. So passing by value into your copy constructor means you need to make a copy before the copy constructor is invoked, but to make a copy you first need to call the copy constructor. Save this answer.

Does copy constructor return anything? ›

Java copy constructor is a particular type of constructor that we use to create a duplicate (exact copy) of the existing object of a class. Copy constructors create and return a new object using the existing object of a class.

Which of the following is true for copy constructor? ›

10. Which among the following is true for copy constructor? Explanation: It can't be defined with zero number of arguments. This is because to copy one object to another, the object must be mentioned so that compiler can take values from that object.

What is the difference between default and copy constructor? ›

The compiler also creates a copy constructor if we don't write our own copy constructor. Unlike the default constructor, the body of the copy constructor created by the compiler is not empty, it copies all data members of the passed object to the object which is being created.

Is copy constructor deep? ›

The default copy constructor and default assignment operators do shallow copies, which is fine for classes that contain no dynamically allocated variables. Classes with dynamically allocated variables need to have a copy constructor and assignment operator that do a deep copy.

Can a copy constructor throw? ›

However, the copy constructor for an exception object still must not throw an exception because compilers are not required to elide the copy constructor call in all situations, and common implementations of std::exception_ptr will call a copy constructor even if it can be elided from a throw expression.

Does copy constructor perform deep copy? ›

Name/Address will have the memory address and shallow copy will copy just the memory address of the actual value. So the copy constructor is 'PERFECT' doing a deep copy.

What are the two situations when a copy constructor executes? ›

In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value. 2) When an object of the class is passed (to a function) by value as an argument.

Does every class have a copy constructor? ›

Like the default constructor, each class has its default Copy constructor in C++. It creates a member-wise shallow copy of objects of that class.

How many arguments can a constructor take? ›

Parameterized constructors in java are the programmer written constructors in a class which have one or more than one arguments. Parameterized constructors are used to create user instances of objects with user defined states. There can be more than one parameterized constructor in a class.

Can one class have more than one constructor? ›

A class can have multiple constructors that assign the fields in different ways. Sometimes it's beneficial to specify every aspect of an object's data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few.

How many maximum constructors can a class have in C++? ›

In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments.

Can you call a constructor twice C++? ›

you cannot call the constructor more than once for a one object but you can call it recursively. The answer depends entirely on how you managed to trick the compiler into generating code that you claim calls the constructor on the same object twice.

Should copy constructor be virtual? ›

No you can't, constructors can't be virtual. 4) A constructor shall not be virtual (10.3) or static (9.4). [...]

What are the advantages of copy constructor in C++? ›

1. The copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. 2. Copy constructor takes a reference to an object of the same class as an argument.

Can constructor be overridden and why? ›

Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden. If you try to write a super class's constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.

Which keyword is not allowed with constructor? ›

Therefore, java does not allow final keyword before a constructor.

Can copy constructor be pass by value? ›

Answer: No, in C++, a copy constructor doesn't support pass by value but pass by reference only.

What type of variable we can pass copy constructor? ›

Explanation: The restriction for copy constructor is that it must be used with the object of same class. Even if the classes are exactly same the constructor won't be able to access all the members of another class. Hence we can't use object of another class for initialization.

Can a copy constructor accept an object of the same class as parameter? ›

Copy constructor has the same form as other constructors, except it has a reference paramter of the same class type as the object itself. C++ requires that a copy constructor's parameter be a reference object. Because copy constructor are required to use reference paramters, they have access to their argument's data.

What is the difference between copy constructor and assignment operator? ›

The difference between a copy constructor and an assignment operator is that a copy constructor helps to create a copy of an already existing object without altering the original value of the created object, whereas an assignment operator helps to assign a new value to a data member or an object in the program.

Which is faster cloning or copying? ›

In theory, it will should be faster to copy files than to clone the drive because when cloning, you must read and write every block on the drive, even the empty ones, whereas with copying you only read and write the data.

Do I have to write a copy constructor? ›

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 memory locations. Hence, in such cases, we should always write our own copy constructor (and assignment operator).

Does every class need a constructor C++? ›

For example, all members of class type, and their class-type members, must have a default constructor and destructors that are accessible. All data members of reference type and all const members must have a default member initializer.

Does every C++ class have a copy constructor? ›

Like the default constructor, each class has its default Copy constructor in C++. It creates a member-wise shallow copy of objects of that class.

What happens if we don't use constructor in C++? ›

The compiler only declares and defines an automatically generated default constructor if you haven't provided any constructor. With a non-instantiable parent class however, it is possible to prevent any kind of constructor from working.

Is constructor important in C++? ›

C++ Constructors. Constructors are methods that are automatically executed every time you create an object. The purpose of a constructor is to construct an object and assign values to the object's members. A constructor takes the same name as the class to which it belongs, and does not return any values.

Do I always need a constructor? ›

Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor.

Can a class have no copy constructor? ›

If no user-defined copy constructors are provided for a class type (struct, class, or union), the compiler will always declare a copy constructor as a non-explicit inline public member of its class.

Does copy constructor exist by default? ›

A copy constructor is automatically invoked by the compiler whenever we pass or return an object by value. We can restrict an object passed or return by value using a private copy constructor. A default copy constructor is fine, but be cautious if there is a dynamic data member.

Can a class work without constructor? ›

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.

What happens if a class has no constructor? ›

If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() . This constructor is an inline public member of its class.

What are the limitations of constructor in C++? ›

The following restrictions apply to constructors and destructors:
  • Constructors and destructors do not have return types nor can they return values.
  • References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
  • Constructors cannot be declared with the keyword virtual.
Apr 3, 2010

What are advantages of constructor in C++? ›

Importance of constructors
  • Constructors are used to initialize the objects of the class with initial values.
  • Constructors are invoked automatically when the objects are created.
  • Constructors can have default parameters.
  • If constructor is not declared for a class , the C++ compiler generates a default constructor.

Can we initialize object without constructor? ›

You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.

Does every class has a constructor? ›

All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.

Can we create object without constructor? ›

Abstract: De-Serialization creates objects without calling constructors. We can use the same mechanism to create objects at will, without ever calling their constructors.

Videos

1. Copying and Copy Constructors in C++
(The Cherno)
2. Copy Constructor in C++ in Hindi
(Edutainment 1.0)
3. Copy Constructor in C++ (TELUGU) | Constructors in C++ | By Sudhakar Bogam | C++ Tutorial
(SB Tech Tuts)
4. Copy Constructor in C++ (HINDI/URDU)
(easytuts4you)
5. Copy Constructors | Explicit Constructors | C++ in Tamil | Logic First Tamil
(Logic First Tamil)
6. COPY CONSTRUCTOR IN C++ ( 33)
(Codearchery)
Top Articles
Latest Posts
Article information

Author: Duane Harber

Last Updated: 03/31/2023

Views: 6286

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.