0

what is a copy constructor?

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



Category: C & C++

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

1

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
}

Answered


0

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.


 

Answered


0

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

Answered


0

new variable is creted
Answered


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