Re: delete an object through its parent - virtual desctructors
Mosfet wrote:
I allocate an object inheriting from GDObject(C struct) -> returned as a
GDAddrBook*(typedef for a GDObject*) to caller and then when I call
GDObject_Release pointer is cast to GDObject* and then delete is called
on it.
Can it work ?
This will never work as expected. Deleting a pointer to a POD type never
invokes any destructor.
You have to do an explicit down cast to a C++ type before invoking
delete on a non POD type though a base class pointer. But since your
reference counting functions do not know the actual type, there will be
no C compatible solution.
However, the method _GDObject_Release may invoke a static deleter
function. In this function you might do the cast to the C++ type. In
fact you need the opposite function of OS_GDAddrBook_Alloc, i.e.
OS_GDAddrBook_Destroy.
Of course, if your objects become polymorphic you need a common base
class with a virtual destructor and the deallocation function only casts
to this base class. Everything else is done by dispatch table.
What I wonder a bit is, that the structure of GDObject is part of the
public interface. Since it is very dangerous to modify cRefs from
outside your library and even read access is only reliable if the result
is 0 or 1, it should be a hidden part of your implementation.
Normally I would recommend that a common base class with a protected
constructor and an protected virtual destructor has cRefs as a private
field initialized to 1 at construction. The class then provides public
static functions for incrementing/decrementing the reference count. This
would encapsulate most of the lifetime management safely.
Marcel