L15 - Copy Constructors

#ece244

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:

  1. Student a(b); where we are:
    1. calling the constructor for a new Student object a
    2. passing in the Student object b, which makes a a copy of b
  2. Student b = a;
    1. b is being created in the same line, so a copy constructor is used
    2. b = a does not call a copy constructor because b is already created, so it just calls operator=
  3. Object is passed by value to a function
  4. 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: