Copy Constructor in C++

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
By Prateek Narang
Free
star5
Enrolled: 1000
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
Prateek Narang
Free
5
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Overview

A copy constructor is a member function of a class that initializes an object with an existing object of the same class. In other words, it creates an exact copy of an already existing object and stores it in a new object.

Scope

  • This article covers the concept of Copy Constructor in C++.
  • It also covers the types of Copy constructors in C++.

Introduction

Classes in Object-Oriented Programming are like entities in real life. Like everything in life, they have their properties and functions, making them what they are. And objects are instances of these entities, or classes, as we call them in Object-Oriented Programming. Like, a Car (with properties such as Color, Price, etc.) is a class, and a WagonR(with Color = ‘Red’ and Price = ‘5 lacs’) is an object of the class Car.

Often while programming, we come across two very similar objects. For example, two cars with the same make and model. Would it make sense to construct an object of this class Car from scratch every time? To handle situations like these, where we need objects similar to ones already existing, we have a copy constructor in C++. In this article, we will see how that works and everything else required to understand the functioning of the copy constructor in C++.

What is a Copy Constructor?

A constructor is used to initialize an object. A copy constructor is a member function of a class that initializes an object with an existing object of the same class. In other words, it creates a copy of an already existing object and stores it in a new object. Consider an object of class Car, WagonR_1. A copy constructor can create another object of this car, which will be the same as WagonR_1, say WagonR_2.

New Object, i.e., WagonR_2, is the exact copy of the existing object. It is possible to make changes in WagonR_2 further and make it entirely different based on what kind of copy it is. Keep reading to understand what that means.

object created using copy constructor in cpp

Types of Copy Constructors in C++

1. Default 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 is a shallow copy of an object?

  • A shallow copy is a reference to the object it is created from, i.e., it creates a new copy of an already existing object, but any changes made to the original object would be reflected in the newly created copy and vice-versa.
  • All objects created using the default copy constructor for an object share the exact memory location. In the new objects, which are called shallow copies, only the memory address of the original object is copied. Hence, they do not acquire any memory of their own.
  • The default copy constructor in C++ can only create a shallow copy of an object.

copy constructor in cpp creates a shallow copy of an object

shallow copy made using default copy constructor in cpp

In the above code sample, newObject is being initialized with the help of the default copy constructor. The programmer does not need to write the definition of the default copy constructor in C++. However, as explained above, it only creates a shallow copy of the existing object.

2. User-defined copy constructor

Like other constructors and destructors, C++ allows its programmers to create their Copy Constructors. These are called User-defined Copy constructors, used to create deep copies of existing objects. These User-defined copy constructors are created as member functions within their respective classes.

What is a deep copy of an object?

  • A deep copy of an object is a true copy, unlike a shallow copy.
  • All deep copies have separate memory allocations, i.e., changes made to the deep copies of an object are not reflected in the original object, and similarly, changes made into the original objects are not reflected in the deep copies.
  • A deep copy of an object can only be created using a User-defined copy constructor in C++. You can find the method to create a user-defined copy constructor later in the article with its required code samples.

deep copy in cpp copy constructor

deep copy made using a user-defined copy constructor in cpp

Syntax to create a Copy Constructor in C++

Like any other constructor in C++, the Copy constructor does not have a return type, not even void. Instead, the member function for the Copy Constructor is created using the following syntax:

The following code describes an example of a simple Copy Constructor in C++:

To find a complete code sample, please go through the provided link to get a well-documented code sample of a sample class describing the workings of the Copy Constructor in C++.

When is the copy constructor called?

The compiler calls the Copy constructor in C++ for the following reasons:

  • When we need to create an object based on another object of the same class.
  • For example, let’s say you have a class called Cars. If you have car experience, you know that each car can have different models. Each model consists of slightly different (upgraded/downgraded) features.
  • You have an object WagonR_1 with all its respective attributes horsepower, engineCapacity, tankCapacity, numberOfSeats, and many more. Now, you need to create WagonR_2, an upgraded version of the pre-existing object WagonR_1. WagonR_2 will have a tankCapacity of 10 more liters than WagonR_1. To do this, you can either create a new object of the class Cars from scratch or use the copy constructor to create a copy of WagonR_1 and update its tankCapacity.
  • When an object needs to be passed by value as the argument of a function.
  • Consider a function int onRoadPrice(Cars obj), which calculates the on-road price of any object of class Cars based on its unique attributes. In this case, the function would create a copy of the object passed to it as an argument and then progress with the function definition. Note: It is also possible to pass objects as references. It is done when we create our user-defined Copy Constructor in C++. But in the case of pass-by-reference, a copy of the object is not created.
  • When a function returns an object by value. Consider a function Cars changeColour(Cars obj1, string c), which takes an object of the class Cars and a string as arguments and returns an object with object.colour equals c. It takes a car and returns a new car with a new colour. In this case, the function would create a copy of the object to return it. Note: It is impossible to return an object by reference because the object goes out of scope at the end of the function, so you cannot return its reference.

Conclusion

In this article, we learned:

  1. What is a copy constructor?
  2. Where is a copy constructor required?
  3. What kind of copy constructors are there in C++?
  4. What kind of copies can a copy constructor generate?
  5. How to create user-defined Copy constructors in C++?
  6. How to syntactically call a Copy constructor in C++?

With this, we hope you better understand Copy constructors in C++. Thank you for reading!

Happy Learning 🙂