Copy Constructor – C++ Programming Questions and answers

(Last Updated On: October 21, 2016)

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?

 

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

Explanation:

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