Overriding Destructors

From MorphOS Library

Revision as of 14:06, 4 January 2011 by Krashan (talk | contribs) (Contents.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Grzegorz Kraszewski


The only task of a destructor is freeing resources allocated in the constructor and other methods (some resources may be allocated on-demand only). In any case the destructor must leave the object in the same state as right after DoSuperMethod()/DoSuperNew() in the constructor. After that the destructor calls a super class destructor. The destructor receives an empty message.

IPTR MyClassDispose(Class *cl, Object *obj, Msg msg)
{
  struct MyClassData *d = (struct MyClassData*)INST_DATA(cl, obj);

  if (d->ResourceA) FreeResourceA();
  if (d->ResourceB) FreeResourceB();
  if (d->ResourceC) FreeResourceC();
  return DoSuperMethodA(cl, obj, msg);
}

The example destructor follows an example of constructor in the Overriding Constructors article. Three resources obtained in the constructor are freed here. The destructor is prepared for partially constructed object, every resource is checked against NULL before freeing. If for some type of resource NULL is a valid handle, an additional flag may be added to the object instance data area.