Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
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 7-Jan-13 0:01am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

hi,
this might give you some idea :
here[^]
and also here[^]
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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.
  Permalink  

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 841
1 OriginalGriff 245
2 Volynsky Alex 205
3 Kishore Pogaru 140
4 Magic Wonder 129
0 OriginalGriff 5,640
1 Sergey Alexandrovich Kryukov 4,693
2 CPallini 4,540
3 George Jonsson 3,132
4 Gihan Liyanage 2,445


Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 7 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100