Basically lines 40 to 50 are about implementing the assignments in lines 3, 4 and 5 of:
1 2 3 4 5
|
Critter a;
Critter b;
b = a;
Critter c = a;
a = a;
|
The class Critter has two member variables:
1 2
|
string* m_pName;
int m_Age;
|
which need to be changed during the assignment process.
Effectively what needs to happen is:
1 2
|
b.m_pName = a.m_pName;
b.m_Age = a.m_Age;
|
This would be easy, apart from two problems. First there is a pointer (m_pName). Secondly what happens if we are assigning to ourselves:
a = a;
Dealing with the second problem, line 43 fixes this, ie no need to do anything! It is worth checking that this works with some test code!
Dealing with the first problem, if we simply copy the pointers:
b.m_pName = a.m_pName;
then both pointers would point to the same data, and when the destructor of one free's that data (line 30), the other will possibly get corrupted when the storage is re-used, or be invalid, or throw an exception when it tries to be free'd a second time. So line 46 allocates new storage for the string, initializes it, and sets the m_pName pointer to point to it. However, what of the original memory pointed to by b.m_pName? It is de-allocated in line 45, so no memory leaks.
This type of problem (copying classes with pointers) is covered very well in a number of places:
http://www.cplusplus.com/articles/y8hv0pDG/
http://pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/CLASSES-PTRS.html
http://stackoverflow.com/questions/5033232/c-class-copy-pointer-copy