Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Copy  Constructor

A  copy  constructor  is  a  constructor  that  executes  when  you  initialize  a  new  object of the  class  with  an existing  object  of  the  same  class.  You  don't  need  to  create  a constructor  for  this;  one  is  already  built  into  all  classes.  It's  called  default  copy constructor.  It's  a  one  argument  constructor  whose  argument  is  an  object  of  the same class.


For  example,

String  s1 ( " hi " ) ;

String  s2 ( s1 ) ;

String  s3 = s1 ;


The  object  s2  is  initialized  in  the  statement   String  s2 ( s1 ) ;

This  causes  the  default  copy  constructor  for  the  String  class  to  perform  a  member-by-member  copy  of  s1  into  s2.  Surprisingly,  a  different  format  has  exactly  the  same effect,  causing  s1  to  be  copied  member-by-member  into  s3:


String  s3 = s1 ;


Although  this  looks  like  an  assignment  statement,  it  is  not.  Both  formats  invoke  the default  copy  constructor,  and  can  be  used  interchangeably


If  we  are  not  satisfied  with  the  default  copy  constructor  we  can  define  a copy constructor  on  our  own.  It  takes  the  form  of  


class_name ( const  class_name  & object_name ) ;



For  example,

String ( const  String  & tmp ) ;



Difference  between  initialization  &  assignment

The  difference  between  initialization  of  an  object  with  another  object,  and  assignment of  one  object  to another  is  this:  Assignment  assigns  the  value  of  an existing  object to another  existing  object;  initialization  creates  a  new  object  and initializes  it  with  the contents  of  the  existing  object.  The  compiler  can  distinguish  between  the  two  by using your  overloaded  assignment  operator  for  assignments  and  your  copy constructor for initializers.


For  example,  the  statement

String   s2 = s1 ;


would  define  the  object  s2  and  at  the  same  time  initialize  it  to  the  values  of  s1.


Remember  the  statement

s2  =  s1 ;


will  not  invoke  the  copy  constructor.  However,  if  s1  and  s2  are  objects,  this statement is  legal  and  simply  assigns  the  values  of  s1  to  s2,  member-by-member. This  is  the task  of  the  overloaded  assignment  operator ( = ).