Copy Constructor
First seen in CS138. Learned in CS247.
Linked List ADT Copy constructor:
Node:: Node(const Node& other): data{other.data},next{other.next ? new Node{*(other.next)} : nullptr}{}
// Copy constructor
Point(const Point &p1) {
x = p1.x;
y = p1.y;
}
Compiler-Provided Copy Constructor
If we don’t provide an implementation of the copy constructor, the compiler provides a default Copy Constructor that simply copies all the fields.
Another example:
class Test {
public:
Test() {};
Test(const Test& t) {
cout << "Copy constructor called " << endl;
};
Test& operator=(const Test& t) {
cout << "Assignment operator called " << endl;
return *this; // to allow for chaining
};
};
Why
*this
and not just*this
?Because
*this
is a pointer. And this makes sense on why you would dothis->data
instead ofthis.data
when you want to access specific member fields.
From CS138 - Introduction to Data Abstraction and Implementation: