What is the difference between the functionality of a copy constructor and an Assignment operator.What is the need of an assignment operator when we can do the same task with a copy constructor.
Asked
Active
Viewed 1,119 times
-6
-
We can not do the same task with a copy constructor for already created object. – Vlad from Moscow Oct 16 '17 at 16:36
-
Read about what [the copy assignment operator](http://en.cppreference.com/w/cpp/language/copy_assignment) does and what [a copy constructor](http://en.cppreference.com/w/cpp/language/copy_constructor) does. Currently your question is equivalent to "Why do we use cars when we have airplanes". – nwp Oct 16 '17 at 16:38
1 Answers
1
What is the difference between the functionality of a copy constructor and an Assignment operator.
Difference is that copy ctor constructs new object with a copy of existing one, assignment operator overrides fully constructed object with a copy. For example if you have a raw pointer to dynamically allocated memory in your class - copy ctor would just allocate necessary memory for it, in assignment operator you have to deallocate it first and then allocate new one. Or you can just copy data to already allocated memory - logic is significantly different.

Slava
- 43,454
- 1
- 47
- 90