Copy Constructor
// 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 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 justthis
?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!
Note about this, it might be dangerous to get confused on. This is actually super important!