what is a copy constructor?

what is a copy constructor?
what is its use and advantages

Category: C & C++ 9 years ago
aparajitha
Asked 9 years ago

Like it on Facebook, +1 on Google, Tweet it or share this question on other bookmarking websites.

copy constructors play a significant role when your class has a pointer as a member variable. The default copy constructor provided by compiler would just make a copy of pointer and wont actually copy the contents pointed by it. This is something called as "shallow copy". You can write your own copy constructor which will have the code to copy the data pointed by pointer. This concept is called "deep copy".

Its copying the content of one object to another object through constructor. Hence the name copy constructor.
Eg:

class abc
{ int x;
abc( abc a) // copy constructor.....
{
x=a.x;
}

abc (int z)
{
x=z;
}
}

void main()
{
abc a(10), b(a); // b(a) calls the copy constructor
}

sajeetharan
Answered 9 years ago
sajeetharan

copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment).



  • A variable is declared which is initialized from another object, eg,
    Person q("Mickey"); // constructor is used to build q.
    Person r(p); // copy constructor is used to build r.
    Person p = q; // copy constructor is used to initialize in declaration.
    p = q; // Assignment operator, no constructor or copy constructor.


  • A value parameter is initialized from its corresponding argument.
    f(p);               // copy constructor initializes formal value parameter.


  • An object is returned by a function.


C++ calls a copy constructor to make a copy of an object in each of the above cases. If there is no copy constructor defined for the class, C++ uses the default copy constructor which copies each field, ie, makes ashallow copy.


 

Raja
Answered 9 years ago
Raja

A copy constructor is  that that comes, whenever a new variable is constructed .

rambabu
Answered 2 years ago
rambabu

new variable is creted
Aakash Agarwal
Answered 6 years ago
Aakash Agarwal

Please register/login to answer this question.  Click here to login