L15 - Copy Constructors
Aside
So it turns out the textbook I was reading from is incomplete. Back to lecture notes it is! If you're wondering where the first half of this lecture is, refer to TB 5.2 - Friend Functions.
cout, along with all other streams, cannot be passed or returned by value, as this would create a copy and produce an error. We can bypass this by using a copy constructor.
what are copy constructors
A copy constructor is a constructor used to create a copy of an existing object. It is automatically called in the following situations:
Student a(b);where we are:- calling the constructor for a new
Studentobjecta - passing in the
Studentobjectb, which makesaa copy ofb
- calling the constructor for a new
Student b = a;bis being created in the same line, so a copy constructor is usedb = adoes not call a copy constructor becausebis already created, so it just callsoperator=
- Object is passed by value to a function
- Object is returned by value by a function
By default, every class has a copy constructor that copies all data members.
In the following code, we define a Student class along with the a(b); constructor, as described above.
class Student {
private:
string name; int ID;
public:
Student(const Student& other) {
name = other.name;
ID = other.ID;
}
}
Notes:
- This is a copy constructor.
- We make sure to pass by reference, because otherwise we would be calling the copy constructor again when we pass the
otherobject in.- When this happens, the new copied object calls the copy constructor again, thus creating a cycle (called recursion - wow, APS105!)