Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying and assignment

Tags:

c++

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?

like image 981
filipok Avatar asked Apr 02 '12 21:04

filipok


2 Answers

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&).

like image 74
Luchian Grigore Avatar answered Oct 21 '22 07:10

Luchian Grigore


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();
like image 35
Oliver Charlesworth Avatar answered Oct 21 '22 09:10

Oliver Charlesworth