+ 11
Copy constructors
Can someone tell me what are the copy constructors for?
2 odpowiedzi
+ 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
+ 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.