Can Copy constructor accept object by value instead of reference?

Answer: No, in C++, a copy constructor doesn’t support pass by value but pass by reference only. It cannot accept object parameter by value and it should always receive it as a reference. An error, “Illegal copy constructor” will be thrown if we receive object by value.

Copy constructor by value:
Syntax : Mobile(const Mobile c_obj)// throws compiler error

Copy constructor by reference:
Syntax : Mobile(const Mobile& c_obj)//OK

REASON:

We know that if use below syntax for class Mobile i.e. initialize the object at the time of object creation, a class copy constructor would get called.

Mobile object1;
Mobile object2 (object1) OR Mobile object2=object1; // in both cases copy constructor get called.

So,If we take by value case i.e. Mobile(const Mobile c_obj),
on calling Mobile object2 (object1), compiler will interpret it as Mobile c_obj= object1;

Again, this the statement would call same copy constructor and same for over and over.

Hence, It goes in recursion.

That’s why it is prevented at the compile time itself.

Example:

// Copy constructor parameter by value throws an 
// Error : Illegal copy constructor


class Mobile{

public:
	Mobile(){}

	// Below copy constructor( object by value) will throw a compile time error i.e.
	//illegal copy constructor: first parameter must not be a 'Mobile'
	/*Mobile(const Mobile obj){ 

	printf("copy constructor by value\n");
	}*/

	//Copy constructor always shoud accept clas object by reference.
	Mobile(const Mobile& obj){
		printf("copy constructor by reference\n");
	}
};

int main()
{
	Mobile object1;
	Mobile object2=object1;//calling copy constructor

	return 0;
}

Can Copy constructor accept object by value instead of reference?

Scroll to top