Copy Constructor – C++ Programming Questions and answers

C++ tricky and conceptual programming questions and answers with explanation asked in technical interviews.

Topic – Copy Constructor, Assignment Operator.


Q – How many times Copy constructor would get called on below function call?

Car&  fun( Car &oldCar)//  line -1
		Car &newCar = oldCar; //line - 2

		return newCar; //line -3


Answer: 0, No copy constructor will be called on this function call.


At line 1- The fun function receive parameter as a reference, means, it refering the old car object passed to it and hence no new object creation – No copy constructor call.

At line 2- Again here, we are assigning the old car reference and making it as a new car. Hence, no copy constructor call here. It’s like we are having the old car object and polising, repairing and maintaning it and making it as a new car.

If it were like Car newCar = oldCar; copy constructor would have been called.

At line 3- This function is returning the same car. Notice the return type i.e. “Car& fun(…)”. it is returning the reference of the car.So, again, no new object creation and no copy constructor call.

If return type were like this “Car fun(…)” copy constructor would have been called.

As a whole, this function recives the old car of a customer, service it and returns the same making it as a new car.

Complete test

class Car{

	Car(){cout<<"Car ctr\n";}//constructor
	Car(const Car& c){cout<<"Car Copy ctr\n";}//copy constructor
	Car&  func( Car &oldCar)// 1
		Car &newCar = oldCar; // 2

		return newCar; // 3
int main()
	Car car; //constructor call
	return 0;
Car ctr


Leave a Comment