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.

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

class Car{

public:
	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
	car.func(car);
	
	return 0;
}
Output:
Car ctr


Q – Explain the following C++ program.

class MyClass{

public:
	
	MyClass(const MyClass &obj)
	{
		printf("Copy Constructor");
	}
};

int main(){

	MyClass obj;

	return 0;
}

Answer:  There is a compiler error i.e. no default constructor available for this class in this program. Note that if we create an object of a class, it calls default constructor, which is not available in the class.

We know that if we write any kind of constructor or copy constructor in the class, compiler will not provide its default constructor. So, we have to write default constructor i.e. empty parameterized constructor in the class. E.g. below class is ok.

class MyClass{

public:

	MyClass(){}// empty constructor 
	
	MyClass(const MyClass &obj)//Copy constructor
	{
		printf("Copy Constructor");
	}
};


Related Posts