views:

384

answers:

1

So i want to overload delete of a abstract virtual class. This will call deleteMe() in the derived class which is in another lib. This is to prevent error/crashes mention here http://stackoverflow.com/questions/443147/c-mix-new-delete-between-libs

when i call delete me from delete in my base class, i get the error "pure virtual func call". Then i find out it has already called my dtor. How do i overload delete or write this code in such a way that it does not call the dtor so i can write delete obj; and have it call obj->deleteMe() which then calls it own delete function and the dtor?

+6  A: 

It sounds like you use operator delete like a normal function that's supposed to do arbitrary things. An operator delete, however, is only supposed to free the memory given to it as the first argument, which is a pointer to that memory area.

That pointer will point to the memory location at where your object was. At this time, however, your object's destructor already ran, and your object doesn't exist anymore. You can't call any member function at all on it - even less so virtual functions!

I have the feeling that you get the purpose of operator delete wrong. If you call delete pointer, the compiler calls the destructor for the object, and then calls the deallocation function to free the allocated memory, which is called operator delete.

Well, why not use the solution that we've shown you earlier, with the boost::shared_ptr?

Johannes Schaub - litb
i am using shared_ptr, when it goes out of scope it crashes. I wanted to have the obj delete naturally with the delete keyword. It looks like i cant do that. Now i am using shared_ptr with std::mem_fun as the 2nd param everywhere. It works well.
acidzombie24
yes, i commented that one guys answer that called delete in addition to calling deleteMe. i believed you call "delete this;" in that function, so he would effectively call delete two times.
Johannes Schaub - litb
i recommended shared_ptr<T> ptr(new T, bind( , but then the other guy posted the other answer, and i removed my comment.
Johannes Schaub - litb