Can Copy constructor accept object by value instead of reference?

(Last Updated On: March 17, 2018)

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: