I am familiar with the simple copy constructors, and it worked fine with classes which members are primitives as strings or integers.
However now I am trying to make a copy constructor for a bit more complex class.
Here is an example code,
there is a class "Modules, a struct "Hardware" and a class "Computer" in which Modules and Hardware are stored.
The member "Computer_Hardware", of the class "Computer", stores a vector of "Hardware" structs.
So how can you make a copy constructor for the class "Computer" ?
I wrote my first thought, but ofc it is not working.
Thanks in advance !
Well it is not fulfilling the function of a copy constructor, since I want to allocate a new instance of the class with the same values, but at a new address.
I tried it however without the new operator, thanks anyways.
Doesn't look like you need to do anything. Just remove the copy constructor and you're done. The implicitly defined copy constructor will do what you want.
I already showed you how to implement your own copy constructor. vector, string and double all support copy semantics. You don't need to create new dynamic instances. Simply copy the individual elements as I showed you above.
The following line create a local pointer to a vector that goes out of scope when the constructor exits creating a memory leak.
std::vector<Hardware>* Computer_Hardware = new std::vector<Hardware>(copy.Computer_Hardware);
Yea thanks for your help, however I still havent solved my problem. It is probably because I have pointers in my classes, so the plain copy doesnt work very well.
If e.g. the struct Hardware and the class Module have pointers, I need to make a deep copy constructor, right?
Do I need to make then only a Computer deep copy constructor or for the struct Hardware and Module aswell?
the copy constructor provided by the compiler will call the copy constructor of the members of your class.
if that behaviour suits you, then let it be.
> If e.g. the struct Hardware and the class Module have pointers,
I'll suggest you to use the smart pointer that gives you the behaviour that you want.