Search for Courses, Topics
certificate icon
Certificate

Learn on Scaler Topics and get certified.

static-certificate

Copy Constructor in C++

Learn about Copy Constructor in C++

17 Aug 2021-7 mins read
quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

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 into 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 like to call them in Object-Oriented Programming. Just 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 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 in C++ 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 an exact copy of an already existing object and stores it into 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

Just 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 shallow copy of an object

shallow copy made using default copy constructor in cpp

//This way, you can create a new object of the class
//sampleClass and initialise it with a pre-existing
//object of the same class.
sampleClass newObject = existingObject;

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, it only creates a shallow copy of the existing object, which has been explained above.

2. User defined copy constructor

Just like other constructors and destructors, C++ allows its programmers to create their own Copy Constructors. These are called User-defined Copy constructors, and they are used to create deep copies of already 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 the 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++

Just 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:

className(const className &objectName);

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

sampleClass(const sampleClass &obj) {
  dataMember1 = obj.dataMember1;
  dataMember2 = obj.dataMember2;
}

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 any experience with cars, 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 litres 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 simply return an object by reference because the object goes out of scope at the end of the function, so you cannot return its reference.
//Example 1: Creating an object based on another object.
Cars wagonR_2 = wagonR_1;
//Updating new objects based on its unique specifications.
//For the sake of this example, consider data members to be public and can be directly accessed by the user for ease. 
wagonR_2.tankCapacity += 10;

//Example 2: Passing an object by value to a function.
int totalCost = onRoadPrice(wagonR_2);

//Example 3: A function returns an object by value.
Cars changeColor(Cars obj1, string c) {
  Cars temp;
  temp.color = c;
  return temp; //Returns object temp of class Cars.
}

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 have a better understanding of Copy constructors in C++. Thank you for reading!

Happy Learning 🙂

Challenge Time!
quiz Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.