I'm using the CPoint class from MFC. There is no explicitly defined assignment operator or copy constructor (AFAIK). Yet, this works:
CPoint p1(1, 2), p2; p2 = p1; // p2 now is equal to p1
I'm assuming this is working automagically because of a compiler generated assignment operator. Correct?
If so, can I be confident that this isn't doing anything unexpected? In this case CPoint is so simple I think all is well, but in general this is something that worries me a bit. Is it better form to do:
p2.SetPoint(p1.x, p2.x);
-cr
This is safe - if an assignment operator wasn't meant to be supplied then the MFC designers could have made sure it wasn't available (by making it private for example).
IIRC the compiler will perform a member-by-member copy, so for a class containing POD like this, you won't have a problem. It can get messy if you have a class that allocates memory and neglects to override operator= and perform a deep-copy.
FWIW I asked a question about what the compiler can and cannot do a while back:
Why don't C++ compilers define operator== and operator!=?
Some of the answers make for interesting reading.
Look up default copy constructor:
http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.html
This isn't a special thing about CPoint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With