Click here to Skip to main content
15,063,596 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi All,

I would like to know why copy constructor always takes reference as a parameter. Why can't it take pointer.

i know that benefit of using reference is to avoid application crash. If you pass object as a reference to any function then compile time checking is done to check object is created/exist.
But if you pass uninitialized/NULL pointer to functions by mistake then that checking is not done at compile time and that is results in to application crash.

but that is something programmer can guarantee to initialize ptr and pass to
copy constructor.

Can anybody tell me what could be the exact reason for choosing references only.

Thanks in advance
Posted

hi,
this might give you some idea :
here[^]
and also here[^]
   
Quote:
I would like to know why copy constructor always takes reference as a parameter. Why can't it take pointer.

Because it makes sense (it makes more sense than passing a pointer): you obtain the same effect with a neater syntax.
Note you may create a constructor accepting a pointer to the object.
   
Since the copy constructor is generated by the compiler when not specified by the user, it make sense to use the same signature for user-defined copy constructor that is used for compiler-defined copy constructor.

If someone define a constructor that take a pointer instead of a reference, then if the caller forget to take the address of the object from which the new object is to be created, then instead of using user-constructor with a pointer, the compiler generated copy constructor (wioth a reference) would be used.

It also make sense to use a reference for consistency. For exemple, all operators like =, ==, <=, += would normally be defined using references.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900