Could somebody explain me the difference between copying and assignment?
SomeClass a;
SomeClass b = a; // assignment
SomeClass c(a); // assignment
b = c; // copying
but what is the difference, why there are two different constructions in the language?
Initialization only happens once, when the object is created. If by copying you mean calling the copy constructor, than copying is a form of initialization. Assignment can happen any number of times.
Now, on to your example, all of those are wrong:
SomeClass a();
This declares a method called a
which takes no parameters and returns an object SomeClass
.
SomeClass b = a; // actually copy constructor & initialization of b
SomeClass c(a); // same
If a
were a SomeClass
object, these two would be initialization, and it calls the copy constructor - SomeClass::SomeClass(const SomeClass&)
. They are equivalent.
b = c; // assignment
If c
is a SomeClass
object, this is assignment. It callse SomeClass::operator =(const SomeClass&)
.
This is initialization (but it calls the copy constructor):
SomeClass b = a;
So is this:
SomeClass c(a);
This is assignment:
b = c;
Oh, and this isn't an initialization:
SomeClass a();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With