When copy constructor is called in C++? – 3 Scenarios Example

(Last Updated On: March 17, 2018)

Answer includes multiple scenarios, when copy constructor is called in C++ programs. The copy constructor  of a class in C++ is invoked on following scenarios in a 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.

C++ Program Example

 

OUTPUT:
Car’s Constructor
Car’s Copy Constructor

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.

C++ Program Example : Both scenarios has been depicted in below C++ program example with comments

 

OUTPUT:
Car’s Constructor
Car’s Copy Constructor
Car’s Copy Constructor