Deallocating some memory

I'm working on an overloaded assignment operator and most of the websites I've visited to get help on doing so have mentioned I need to deallocate any memory that the current class is using internally before I start allocating// assigning new memory. What does this mean? What memory am I supposed to deallocate in my overloaded assignment operator before I start assigning things to each other?

For example, the objects I'm trying to assign to each other are both of type "Heap":

1
2
3
4
5
class Heap{
private:
Queue<T> * items[MAX_HEAP];
         int          size;             /** Number of heap items. */
}


When I assign one to another, what do I need to delete?
Oh ok. If you're using dynamic memory (I hope you know what that is), then if you want to make an object = a different object of the same class, then you would need to clear the first object's data to make room to copy the second object's data.

Now. This usually is only necessary if you have any dynamic objects inside the class. You would have to design more of your Heap class before anyone can help you specifically.
Last edited on
closed account (zb0S216C)
hopesfall wrote:
"When I assign one to another, what do I need to delete?"

You don't have to delete anything. You can simply pass ownership to the left-hand class. However, to overload the assignment operator successfully, it'll have to resemble this:

1
2
3
4
5
Heap &operator = (const Heap &Instance)
{
    // ...
    return(*this);
}

Note that Instance must be a reference to a constant Heap. If it's not, the compiler will generate it's own assignment operator (not what you want with your class). That said, deleting Instance's memory, or even claiming ownership of Instance's memory would violate the const-correctness rule. There's two ways around this:

1) Declare Heap::items mutable
2) Create a member function that acts like an assignment operator

Also, make sure you check for self-assignment.

Wazzak
Thanks for the replies, guys. In regards to the first answer:
"then if you want to make an object = a different object of the same class, then you would need to clear the first object's data to make room to copy the second object's data."


What if I'm doing something like: obj1 = obj2 where obj 2 is a filled Heap and obj1 is an empty (new instance) Heap? Is there anything to delete then? Would I need to check if obj1 is empty first?
Last edited on
Topic archived. No new replies allowed.