I don't think my deconstructor is working properly
the message in the deconstructor, to let the user know it worked properly, is not showing on my output, and I cannot for the life of me find where the problem lies
I might be wrong about this but I do not think do not want to reallocate memory, I think your just initializing a pointer that does not exist in this case, inside of your destructor.
All that should be there are instructions of what to delete.
I would assume unexpected behavior with the way your code is written
Also look at your code in a debugger. That will tell you what is actually happening.
So you delete a pointer.
Then set a pointer, that does not exist to null
Then cout your reallocating memory.
1 2 3 4
~Myclass()
{
delete ptr;
}
I would just run the above code like so.
I have not tired to compile the above code, but I think you may be doing too much in your destructor. Just bring it back have it do one job. E.g deleting objects/freeing memory.
You might have to traverse your object and delete each allocation of your array.
e.g
create a
bool IsEmpty()
method.
then in your destructor
1 2 3 4 5 6 7 8
~Myclass()
{
while(!IsEmpty())
{
delete ptr; // removed the [] because you would be looking at each array member.
}
cout << "Memory reallocated!" << endl;
}
you might be able to call your current object using
1 2 3 4 5 6 7 8 9
~Myclass()
{
while(this->!IsEmpty())
{
delete ptr; // removed the [] because you would be looking at each array member.
}
cout << "Memory reallocated!" << endl;
}
When main hits system("PAUSE"); the program hasn't ended yet, so the destructors won't have been called yet.
Look for the output to flash briefly as the window closes.
Try this: Write a simple function with a local MyClass object declared. You should see the dtor output when the function returns and the local MyClass is destroyed.
P.S. Your copy ctor isn't copying anything and it just throws away the block of memory allocated to the local variable int *ptr;
Try writing a displayContents() function then see what object C contains.
Sorry I am going back and forth on this while working on something that is due tonight.
I did not test any of my code that I gave you.
1 2 3 4 5 6 7 8 9 10
~Myclass()
{
if (ptr != NULL)
{
delete ptr; // you need to increment your pointer some how, to traverse your array
// like you pointed out this would only be the front of your pointer array
cout << "Memory reallocated!" << endl;
}
}
int *i;
int *ia;
i = newint; // only 1 int
ia = newint[5]; // array of 5 ints
delete i;
delete [] i; // if you use new foo[xxx] you need to use delete [] foo