Presentation is loading. Please wait.

Presentation is loading. Please wait.

Class: Special Topics 2 For classes using memory allocation

Similar presentations


Presentation on theme: "Class: Special Topics 2 For classes using memory allocation"— Presentation transcript:

1 Class: Special Topics 2 For classes using memory allocation
Destructors Deep vs. Shallow Copy Assignment Operator

2 Destructors A destructor is a method that is called automatically when a class instance is destroyed (de-allocated from memory) The opposite of a constructor which is used to create a class instance Defined with a tilde (and no parameters): ~ClassName(); Explicit definition is not required If not defined, compiler will call a default destructor and automatically remove all members Destructor should be defined if the class does explicit memory allocation (ex: using the new operator) Destructor should explicitly free any allocated memory (ex: using delete) If not done, pointer to memory will be destroyed, but memory will remain allocated with no way to reference it!

3 Deep vs. shallow copy Important to do a deep copy when making a copy of a class instance where memory is explicitly allocated in a class (ex: using new) Avoids problem of having compiler attempts to access deallocated memory Shallow copy Just copy the original pointer value to the pointer in the copied instance Result is that both the original and copied pointers have the same value i.e. point to the same memory location Deep copy Allocate new memory in the copied instance Copy the contents of the original instance to the new memory Result is two independent instances with their own copy of the same data values

4 Assignment operator Must test for self-assignment Otherwise…
If the class does memory allocation Ex: A = A Otherwise… When the existing storage is deallocated, there will be nothing to copy!!! Note also necessary in copy constructors!!! MyClass& MyClass::operator=(const MyClass &rhs) { // Check for self-assignment! if (this == &rhs) // Same object? return *this; // Yes, so skip assignment, // and just return *this. ... // Deallocate, allocate new space, // copy values... return *this; // for cascading! }


Download ppt "Class: Special Topics 2 For classes using memory allocation"

Similar presentations


Ads by Google