Tuesday, February 21, 2012

What is copy constructor in C++?

Copy constructor: Is a special constructor to initialize a new object from the existing object. This can be used where the new instance is needed before copying the values. below are the some of the scenarios.

  • Creating the new object and assigning the existing object to the newly created object
  • Passing a object by value
  • When a object is returned by function by value

class Copy{

    Copy()  //constructor
       //cout< < "constructor "< < endl;
    Copy(const Copy &o) // copy constructor
        cout< < "copy constructor "< < endl;
void test(Copy C)
int main()
    Copy C1;
    Copy C2=C1; //calling copy constructor (creating n assigining - 1st scenario)
    test(C1);   //calling copy constructor (passing object by value - 2nd scenario)

 for copy constructor , need to pass the object as a reference, and not by value. The reason behind this is, when you pass the object by value will call the copy constructor, so calling copy constructor is itself passing object by value, this will become infinite loop until memory reaches empty. Earlier compilers will get run time error, but latest compilers will give the compilation error if you not use reference.

No comments:

Popular Posts