Copy constructor and its usage with simple example? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Copy constructor and its usage with simple example?

15th Aug 2017, 7:44 PM
Sai Krish
Sai Krish - avatar
6 Answers
+ 4
Thank you @EagleEye!
15th Aug 2017, 10:20 PM
Manual
Manual - avatar
+ 3
lets say we have a class Car. Than the copyconstructor would look like this: Car(const Car & other) You can use this to copy data from an existing object when declaring a new object like: Car BMW1(arguments,...); Car BMW2(BMW1); or (i think) also when assigning it like this (if you dont have a definition for operator=()): Car BMW1(arguments,...); Car BMW2 = BMW1; and i think the copy constructor is also used in the following cases: 1) when passing Car obj by value to a function 2) when returning Car obj created inside a function (on the stack not heap) These are all the cases where there is a copy constructor required. If you don't define a copy constructor then the member variables are just copied which can be a problem when you have pointer member vars. (correct me if i'm wrong somewhere)
15th Aug 2017, 9:52 PM
EagleEye
EagleEye - avatar
+ 2
Which language?
15th Aug 2017, 8:06 PM
Manual
Manual - avatar
0
in C++ to be exactly
15th Aug 2017, 8:10 PM
Sai Krish
Sai Krish - avatar
0
no problem!
15th Aug 2017, 10:21 PM
EagleEye
EagleEye - avatar
0
Thanks EagleEye
16th Aug 2017, 5:26 AM
Sai Krish
Sai Krish - avatar