Copying is for initializing new objects by copying the contents of existing ones, assignment is for overwriting existing objects with the contents of other objects - the two are very different things. In particular, this
SomeClass a;
SomeClass b = a;
is copy initialization - you're copying a
to create a new SomeClass called b
using syntax of the form
T x = y;
This has the effect of invoking SomeClass
's copy constructor (assuming there is one and it's accessible). The compiler-generated default copy constructor would do a memberwise copy of a
; you can replace it with your own as needed, e.g.
SomeClass(const SomeClass& rhs)
: x(rhs.x)
{}
(Note that this is a very boring example, as it just does what the default memberwise copy constructor might.)
Moving on, this
SomeClass c(a);
is direct initialization using the copy constructor. It will generally have the same effect as the above, but this is worth a read:
http://www.gotw.ca/gotw/036.htm
Also, see here:
http://www.gotw.ca/gotw/001.htm
Your final case, namely
b = c;
is assignment. The semantics of this should generally be to overwrite b
with the contents of c
(although some things, such as std::auto_ptr
, have strange assignment semantics, so watch out). To implement your own assignment operator, you write something like this (note that this is a very boring example, as it just does what the default memberwise assignment operator might):
SomeClass& operator=(const SomeClass& rhs)
{
x = rhs.x;
return *this;
}
In practice, however, you have to be careful about exception safety in situations like this, which leads to things like the popular copy-and-swap idiom for implementing assignment operators. See here:
http://en.wikibooks.org/wiki/More_C++_Idioms/Copy-and-swap