Copy Constructors

why copy constructor must pass by reference?

My initial thought was this

1
2
3
4
5
6
7
8
9
10
11
class c1
{
   int *p1;

   public:
   c1() { // allocate memory for p1 }
   ~c1() { // deallocate memory for p1 }
     
};

c1 obj1;


if we then try to do c1 obj2(obj1) then if we use c1(c1 obj), then we would leave obj1 with a bad pointer p1.

am i rite? is there any other reason?
That's not the reason. The copy constructor couldn't have possibly been defined as taking an instance of the type.
T(T instance);
If the copy constructor takes a copy of an instance, how is that copy going to be constructed?

The other possibility would have been to pass a pointer, but then the first lines of every copy constructor ever would have been
1
2
3
T(const T *p){
    if (!p)
        return;
Passing references is usually more convenient for both the caller and the callee.
Great answer helios.. Thanks!!
Topic archived. No new replies allowed.