0

Possible Duplicate:
What is The Rule of Three?

I have read in my book about rules of three when you design class in C++:

If you define any one of three in class, then you should define all of three.
1) destructor
2) copy constructor
3) Copy assignment constructor

I understand how to implement those in C++. But I cannot explain myself why we should do ALL of three when we already has one. what the connection between this, please tell me.

Thanks :)

Community
  • 1
  • 1
hqt
  • 29,632
  • 51
  • 171
  • 250
  • By the way, you mean *Copy assignment* ***operator***. – chris Nov 16 '12 at 12:28
  • If you write one of them, obviously your class has special construction / copy / destruction needs. *Not* implementing one of the three would mean you didn't cover all cases of construction / copying / destruction, leaving cases uncovered and possibly resulting in hard-to-trace errors. – DevSolar Nov 16 '12 at 12:29
  • It's because if you have (say) a destructor, then it's usually because your class 'owns' some resource, maybe it allocated some memory, or it opened a file. If that is the case then you usually need to write an assignment operator and a copy constructor to manage ownership of that resource when your object is copied. Otherwise you end up with two objects owning the same resource and both will try to free that resource in the destructor. – john Nov 16 '12 at 12:30
  • Short answer: if the destructor releases a resource, then you need to make sure a copy of the object won't try to release the same resource a second time. Long answer: read the duplicate. Or read more of your book; I would hope that it explains its assertions. – Mike Seymour Nov 16 '12 at 12:30
  • 2
    @hqt Congrats for reading a book, it's seems a rare thing in these days of the internet. – john Nov 16 '12 at 12:31

1 Answers1

1

Basically the reason to define one of them (and not rely on the automatic mechanisms), that same reason counts for the other 'constructors' as well.

paul23
  • 8,799
  • 12
  • 66
  • 149