+ 11

Copy constructors

Can someone tell me what are the copy constructors for?

16th Nov 2016, 9:39 PM
Rebeka Asryan
Rebeka Asryan - avatar
2 Réponses
+ 8
This may sound corny, but copy constructor is constructor that copies attributes of another class instance. Example: class Point{ double x, y; ... // This is copy constructor Point(const Point &anotherPoint){ x = anotherPoint.getX(); y = anotherPoint.getY(); } }; Try it yourself: http://www.sololearn.com/app/sololearn/playground/caDFSvMKHN0H/ https://code.sololearn.com/caDFSvMKHN0H
16th Nov 2016, 11:00 PM
Vladimir Honcharenko
Vladimir Honcharenko - avatar
+ 6
When a class is responsible for an object accessed through a pointer, making a default copy (T t2 = t1) will result in different variables pointing to the same resource. A copy constructor (T(const T& a)) with a copy assignment (T& T::operator=(const T& a)) will do a clean copy so as to get 2 different resources but with same content.
16th Nov 2016, 10:05 PM
Jean-Hugues de Raigniac
Jean-Hugues de Raigniac - avatar