Learn copy constructor in C++ with example, 3 scenarios where it is invoked, note and important points.
What is Copy Constructor in C++:
The copy constructor is a constructor which initializes an object from an existing object of the same class as shown below.
//Create an object of the Car
Car oldCar; // object that also call constructor
//Create an object from existing object
Car newCar = oldCar;// call copy constructor
Syntax in C++:
Considering an example of a Car class, here is the syntax of the copy constructor you write in the class.
Car(const Car& c)
NOTE: notice the const keyword and & operator used in the parameter of the constructor. First read the code example given below, then I will describe the both const and &.
Code Example:
#include<iostream>
using namespace std;
class Car {
public:
//Constructor
Car() { cout << "Car constructor\n"; }
//Copy constructor
Car(const Car& c)
{
cout << "Car Copy constructor\n";
}
};
int main() {
//Create an object of the Car
Car oldCar; //also constructor call
//Create an object from existing object
Car newCar = oldCar;// call copy constructor
return 0;
}
Most Important points about copy constructor in C++:
When you create a new object and at the same time if you initialize it with existing one (Car newCar = oldCar ), then the copy constructor will be called.
If you write the statement as below, the copy constructor will not be called but assignment operator.
Car newCar;
newCar = oldCar;
Why Const keyword and & operator used in the parameter:
Car(const Car& c){ }
The const keyword is used in the parameter so that the existing object coming in the parameter from outside should not be modified.
The & operator is used so that the object received is by reference in the parameter. If you don’t use the &, reference operator in the copy constructor as given below, it will fall in recursion.
Car(const Car c)
Reason for recursion,
Consider, an oldCar object is received in the C variable in Car(const Car c). for simplicity it will look like given below statement.
Car c = oldCar;
You know that at the time new object creation, if initialized with another object, copy constructor will be called.
Hence, again, it will call the copy constructor.
And so on, resulting in recursion, infinite call.
You can read more in the interview question asked : Can Copy constructor accept object by value instead of reference?
3 Scenarios where the Copy Constructor is invoked in C++ program.
Scenario 1: At the time of creating an object, when we initialize it with another existing object of same class type. For example, Car obj2= obj1; if a class is Car.
Scenario 2: When an object of the same class type is passed by value as a parameter to a function.
Scenario 3: When a function returns an object of that class by value.
Read all scenarios in detail here: 3 scenarios where copy constructor is invoked.
Additionally, read programming questions and answers on copy constructors asked in an interview.