dfg
dfg

Reputation: 797

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

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?

Upvotes: 5

Views: 57

Answers (2)

Martin Ba
Martin Ba

Reputation: 38891

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.

Upvotes: 1

Photon
Photon

Reputation: 3222

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.

Upvotes: 2

Related Questions