0% found this document useful (0 votes)
107 views

Copy Constructor in C++: Start Your Coding Journey Now!

The document discusses copy constructors in C++. A copy constructor initializes an object using another object of the same class. It makes a copy of the existing object. The copy constructor is called when an object is returned by value, passed by value to a function, or constructed based on another object of the same class. A user-defined copy constructor is needed when the class contains pointers or dynamically allocated memory to perform a deep copy.

Uploaded by

vinay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views

Copy Constructor in C++: Start Your Coding Journey Now!

The document discusses copy constructors in C++. A copy constructor initializes an object using another object of the same class. It makes a copy of the existing object. The copy constructor is called when an object is returned by value, passed by value to a function, or constructed based on another object of the same class. A user-defined copy constructor is needed when the class contains pointers or dynamically allocated memory to perform a deep copy.

Uploaded by

vinay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Copy Constructor in C++ - GeeksforGeeks https://www.geeksforgeeks.

org/copy-constructor-in-cpp/

Data Structures Algorithms Interview Preparation Topic-wise Practice C++ Java Python

Copy Constructor in C++


Difficulty Level : Medium ● Last Updated : 28 Jun, 2021

We have discussed an introduction to Constructors in C++. In this post,


the copy constructor is discussed.
What is a copy constructor? 
A copy constructor is a member function that initializes an object using
another object of the same class. A copy constructor has the following
general function prototype: 

ClassName (const ClassName &old_obj);

Following is a simple example of copy constructor. 

CPP

#include<iostream>
using namespace std;

class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge
Start Your Coding Journey Now!
that you have read and understood our Cookie Policy &Login
// Copy constructor
Privacy Policy Register

Point(const Point &p1) {x =Got It ! y = p1.y; }


p1.x;

1 of 11 12-02-2022, 07:10 pm
Copy Constructor in C++ - GeeksforGeeks https://www.geeksforgeeks.org/copy-constructor-in-cpp/

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 = 15


p2.x = 10, p2.y = 15

When is  copy constructor called? 


In C++, a Copy Constructor may be called in 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. 
3. When an object is constructed based on another object of the same
class. 
4. 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). 
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge
Source: https://www.geeksforgeeks.org/g-fact-13/
Start Your Coding Journey Now!
that you have read and understood our Cookie Policy &Login
Privacy Policy Register
   Got It !

2 of 11 12-02-2022, 07:10 pm
Copy Constructor in C++ - GeeksforGeeks https://www.geeksforgeeks.org/copy-constructor-in-cpp/

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 filehandle, a
network connection..etc.
The default constructor does only shallow copy. 

Deep copy is possible only with user defined copy constructor. In user
defined copy constructor, we make sure that pointers (or references) of
copied object point to new memory locations.  

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge
Start Your Coding Journey Now!
that you have read and understood our Cookie Policy &Login
Privacy Policy Register
Got It !

3 of 11 12-02-2022, 07:10 pm
Copy Constructor in C++ - GeeksforGeeks https://www.geeksforgeeks.org/copy-constructor-in-cpp/

Copy constructor vs Assignment Operator 


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

CPP

MyClass t1, t2;


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

Copy constructor is called when a new object is created from an existing


object, as a copy of the existing object. Assignment operator is called
when an already initialized object is assigned a new value from another
existing object. In the above example (1) calls copy constructor and (2)
calls assignment operator. See this for more details.
Write an example class where copy constructor is needed?
Following is a complete C++ program to demonstrate use of Copy
constructor. In the following String class, we must write copy
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge
constructor. that you have read and understood our Cookie Policy & Privacy Policy
Start Your Coding Journey Now! Login Register
Got It !

4 of 11 12-02-2022, 07:10 pm
Copy Constructor in C++ - GeeksforGeeks https://www.geeksforgeeks.org/copy-constructor-in-cpp/

CPP

#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);
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge
Start Your Coding Journey Now!
int main() that you have read and understood our Cookie Policy &Login Privacy Policy Register
{ Got It !
String str1("GeeksQuiz");

5 of 11 12-02-2022, 07:10 pm
Copy Constructor in C++ - GeeksforGeeks https://www.geeksforgeeks.org/copy-constructor-in-cpp/

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

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


code? 
If we remove 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. 

CPP

#include<iostream>
#include<cstring>
using namespace std;

class String
{
private:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge
Start Your Coding Journey Now!
char *s;
that you have read and understood our Cookie Policy &Login
Privacy Policy Register
int size;
public: Got It !

6 of 11 12-02-2022, 07:10 pm
Copy Constructor in C++ - GeeksforGeeks https://www.geeksforgeeks.org/copy-constructor-in-cpp/

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("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
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge
Start Your Coding Journey Now!
GeeksforGeeks that you have read and understood our Cookie Policy &Login
Privacy Policy Register
GeeksforGeeks
Got It !

7 of 11 12-02-2022, 07:10 pm
Copy Constructor in C++ - GeeksforGeeks https://www.geeksforgeeks.org/copy-constructor-in-cpp/

Can we make 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 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 copy constructor would be made to call 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? 
See https://www.geeksforgeeks.org/copy-constructor-argument-
const/ 
This article is contributed by Shubham Agrawal. If you like
GeeksforGeeks and would like to contribute, you can also mail your
article to [email protected]. See your article appearing
on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to
share more information about the topic discussed above.

Want to learn from the best curated videos and practice problems,
check out the C++ Foundation Course for Basic to Advanced C++ and
C++ STL Course for foundation plus STL.  To complete your preparation
from learning a language to DS Algo and many more,  please refer
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge
Start Your Coding Journey Now!
Complete Interview Preparation
that you have read our Cookie Policy &Login
and understoodCourse. Privacy Policy Register
Got It !

8 of 11 12-02-2022, 07:10 pm
Copy Constructor in C++ - GeeksforGeeks https://www.geeksforgeeks.org/copy-constructor-in-cpp/

Like 265

Previous Next

Constructors in C++ Destructors in C++

R ECO M M E N D E D A RT I C L E S Page : 1 2 3

01 Advanced C++ | Virtual Copy


Constructor
05 When Should We Write Our
Own Copy Constructor in C++?
29, Oct 11 12, Jul 10

06 Why copy constructor

02 Copy Constructor in Java


22, Nov 11
argument should be const in
C++?
22, Sep 13

03 When is a Copy Constructor


Called in C++?
07 Different methods to copy in
C++ STL | std::copy(), copy_n(),
24, Apr 10 copy_if(), copy_backward()
16, Jun 17

04 Copy Constructor vs
Assignment Operator in C++
08 Shallow Copy and Deep Copy in
C++
17, Jan 11 29, Dec 20

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge
Start Your Coding Journey Now!
that you have read and understood our Cookie Policy &Login
Privacy Policy Register
Got It !

9 of 11 12-02-2022, 07:10 pm
Copy Constructor in C++ - GeeksforGeeks https://www.geeksforgeeks.org/copy-constructor-in-cpp/

Article Contributed By :

GeeksforGeeks

Vote for di�culty


Current di�culty : Medium

Easy Normal Medium Hard Expert

Improved By : harshitSingh_11, aman21810250

Article Tags : cpp-constructor, C++, School Programming

Practice Tags : CPP

Improve Article Report Issue

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

Load Comments

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge
Start Your Coding Journey Now!
that you have read and understood our Cookie Policy &Login
Privacy Policy Register
Got It !

10 of 11 12-02-2022, 07:10 pm
Copy Constructor in C++ - GeeksforGeeks https://www.geeksforgeeks.org/copy-constructor-in-cpp/

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us Algorithms

Careers Data Structures

Privacy Policy Languages

Contact Us CS Subjects

Copyright Policy Video Tutorials

Web Development Contribute


Web Tutorials Write an Article

HTML Write Interview Experience

CSS Internships

JavaScript Videos

Bootstrap

@geeksforgeeks , Some rights reserved

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge
Start Your Coding Journey Now!
that you have read and understood our Cookie Policy &Login
Privacy Policy Register
Got It !

11 of 11 12-02-2022, 07:10 pm

You might also like