Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a object be passed as value to the copy constructor

Tags:

c++

I have some confusion with this "Can a object be passed as value to the copy constructor" The compiler clearly rejects this, which means it is not possible. Can you help me understand this?

class Dummy{
    Dummy(Dummy dummy){ // This is not possible
    }
};

Then why is it said that "Copy constructor will lead to recursive calls when pass by value is used."

like image 376
Zuzu Avatar asked Dec 08 '10 19:12

Zuzu


2 Answers

This is because in order to pass by value, you need to COPY the object. Therefore, you are passing in a copy of the object, in the definition of how to copy it.

Effectively what really happens if this trap is not there, is your copy constructor will call your copy constructor to create a copy, which will call your copy constructor to create a copy, which will call your copy constructor to create a copy, ...

like image 199
Donald Miner Avatar answered Sep 22 '22 14:09

Donald Miner


No.

As the error says, it will lead to recursive calls of the copy constructor. The copy constructor is used to copy an object. You need to make a copy of an object when it is passed by value.

So, if you could have such a constructor, you would need to invoke the copy constructor to copy the object you pass to the copy constructor, ad infinitum.

like image 25
James McNellis Avatar answered Sep 24 '22 14:09

James McNellis