+ 1
Copy constructor and its usage with simple example?
6 Respuestas
+ 4
Thank you @EagleEye!
+ 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)
+ 2
Which language?
0
in C++ to be exactly
0
no problem!
0
Thanks EagleEye