Hi everyone!
I try to delete a derived_class-object using a base_class-pointer. i read that i need a virtual destructor to do this properly but it doesnt seem to work.
class base
{
public:
int x;
base(){x=1;};
virtual ~base(){};
};
class derived :public base
{
public:
int y;
derived(){y=2;};
~derived(){};
};
int main()
{
base* test = new derived();
cout << test->x<<"\n";
delete test;
cout << test->x<<"\n";
return 0;
}
it seems the object still exists after calling delete since "1" is printed to the screen twice.
What am i doing wrong? do i have to add something to the destructor?
interestingly it works when i dont manually declare the destructors...but i was told this causes memory leaks...
any ideas?
It is working as intended. When you delete a pointer, the memory is freed, but the pointer is still pointing at that area. You have just gotten lucky and the memory still happened to exist inside your programs memory so you didn't get a segfault.
And as for your second statement, yes, it does cause memory leaks because only the base destructor would be called in that instance, meaning derived class resources won't be freed.
that way ill know whether the destructor has been called but i wont know whether the destructor deleted the object properly...do i just have to rely on the destructor working correctly?
delete does two things. First, it runs the body of the destructors, starting with the most derived class and
working towards the base. Second, it frees the memory that was allocated to the object on the
corresponding new.
new and delete work. If you give delete a pointer allocated by new, then delete works. If you give
delete a bad pointer, then delete will do nothing good, but it's your programming error.
The language makes no guarantees obviously regarding the correctness of the body of the destructors
since they are provided by the programmer.
I am sure it works in some implementations. But it could change with a different version of gcc, for example. Also the new and delete operators can be overloaded to behave differently.
So even if the default new and delete work on your current compiler version, there is no saying that the same compiler version will give the same result in two different parts of the same project.