when is copy constructor called ?

There are 3 situations in which the copy constructor is called:
1. When we make copy of an object.
string s1(“hello”);
string s2(s1); // copy constructor activated

// create an object as a copy of a temporary object
string s3(string(“abc”));

string s4 = s1;
Line line2 = line1; // This also calls copy constructor
line2=line1 // Calls assignment operator
2. When we pass an object as an argument by value to a method.

// required to maintain state of an object.
3. When we return an object from a method by value.

Default copy constructor does a very simple operation, they will do a bit-wise (member-wise) copy of an object, which means that the object will be copied bit by bit which is dangerous as in that case if it contains a pointer then it means two pointer to a memory location which can lead to crash.

function(str); // str is an string class object.pass by value will invoke copy constructor. Destructor will be called at end and as a result this pointed address will be freed which will result in crash if this str is used again.In case the object has a pointer.
function(str); // program crash
Copy Constructor is called when an object is passed as value since its not the alias which is passed it’s the copy of the object.

What is importance of const. pointer in copy constructor?

Why Call Copy Constructor by passing the class object by  Reference :

 

Resolving technical problems:

Solve your technical problems instantly

We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM

Mail your problem details at writeulearn@gmail.com along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.

One thought on “when is copy constructor called ?”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.