The copy constructor is a constructor, it creates an object. In particular, the copy constructor creates an object which is semantically identical to another, already existing object, of which it makes a "copy":
Person newperson(oldperson); // newperson is a "copy" of oldperson
The assignment operator isn't a constructor at all, but an ordinary member funcion that can only be invoked on an existing object. Its purpose is to assign to your object the semantics of another object, so that after the assignment the two are semantically identical. You are not usually "overloading" the assignment operator, you are just defining it.
Person p; // construct new person
/* dum-dee-doo */
p = otherperson; // assign to p the meaning of otherperson, overwriting everything it was before
// invokes p.operator=(otherperson)
Note that if it makes sense to compare to objects (with ==
), then both copy construction and assignment should behave so that we have equality afterwards:
Person p1(p2);
assert(p1 == p2);
p1 = p3;
assert(p1 == p3);
You are not forced to guarantee this, but users of your class will usually assume this behaviour. In fact, the compiler assumes that Person p1; Person p2(p1);
entails p1 == p2;
.
Lastly, as a final aside and as said elsewhere, note that Person p = p2;
literally means Person p(p2)
(copy construction), and never Person p; p = p2;
. That's syntactic sugar to allow you to write naturally-looking code without compromising efficiency (or even correctness, as your class may not even be default-constructible).