Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there situations where it would be a good idea to write your own copy constructor but not your own assignment operator?

Tags:

c++

The question is pretty self explanatory. If you are required to create one of them does that imply you have to create the second one too?

like image 717
dfg Avatar asked Oct 19 '22 23:10

dfg


2 Answers

The usual need to write these is, as mentioned in the comments above.

However, one can imagine other needs that fit your question. For example, if you want to count the number of objects in your program. A copy constructor will need to increment a counter, whereas an assignment does not change the number of objects, and therefore the default will do.

like image 118
Photon Avatar answered Oct 29 '22 21:10

Photon


When it does not make sense to assign-to an object of a certain type, you do not write/delete the assingnment op. It still might make sense to have a copy ctor though.

A technical example is a class with reference members. Copy construction is possible, copy assignment not really as you cannot change what the ref members point to.

like image 40
Martin Ba Avatar answered Oct 29 '22 20:10

Martin Ba