+ 1

Can anyone tell me please what is the copy constructor in c++ and why and where we need it?

22nd May 2018, 8:59 PM
Hala Hala
Hala Hala - avatar
5 Réponses
+ 3
a copy constructor is when you have some sort of object A and you want to create an object with the same parameters, lests say, B. instead of overloading = operator, you go with the copy constructor and just write NyType B(A). Can be useful in cases when you have those transmutations of weapons in games for example, where you create a weapon from the other one and you just do it by a copy constructor, or when one object dictates how other object look, maybe in some AI implementstion when you tweak the copy constructor a little and create a lot of new object in each generation
22nd May 2018, 9:54 PM
Paul
+ 3
@Zeke Williams there is a difference between copy assignment and copy constructor.
23rd May 2018, 9:30 AM
---
--- - avatar
+ 2
It’s often also necessary to avoid problems coming from deep or shallow copy behavior. See this link for more information : https://stackoverflow.com/questions/14063791/double-free-or-corruption-but-why the first answer should answer your questions
22nd May 2018, 11:16 PM
Max
Max - avatar
+ 2
@Paul has one of the many reasons a copy constructor exists, but I think you should definitely give @Max 's link a read. As a beginning coder, I don't think you will have to worry as much about whether you are shallow or deep copying. That said, a copy constructor is called whenever you assign an object to another object of the same class, when you pass an object by value, and many other cases as well. Paul, your answer was great, but most of the time, you are probably calling the copy constructor without knowing it. In fact, you don't even need to define one yourself, as the compiler will perform a "member-wise copy by values." Basically this means that when you do this: Object obja, objb; obja = objb; It will copy all of the values of objb's variables into obja's variables. You will want to define your own copy constructor when you start using pointers as instance variables, because copying pointers works much differently than other data types. Here is how a traditional copy constructor looks: Object { public: int id; //copy constructor Object(const Object& other) { this->id = other.id; };
23rd May 2018, 1:50 AM
Zeke Williams
Zeke Williams - avatar
+ 1
Ozren Zaric you make an excellent point. I was thinking of mentioning that whenever you need to write your own copy constructor, you will also need to write your own assignment operator overload as well, but I felt I had written too much at that point. Especially for someone just beginning to understand these concepts.
23rd May 2018, 4:21 PM
Zeke Williams
Zeke Williams - avatar