Difference between revisions of "Overriding Destructors"

From MorphOS Library

(Contents.)
 
m
Line 2: Line 2:
  
  
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.
+
The only task of a destructor is freeing resources allocated by 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)
 
  IPTR MyClassDispose(Class *cl, Object *obj, Msg msg)
Line 14: Line 14:
 
  }
 
  }
  
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.
+
The example destructor follows the example of the constructor in the [[Overriding Constructors]] article. Three resources obtained in the constructor are freed here. The destructor is also prepared for a 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.

Revision as of 07:50, 7 January 2011

Grzegorz Kraszewski


The only task of a destructor is freeing resources allocated by 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 the example of the constructor in the Overriding Constructors article. Three resources obtained in the constructor are freed here. The destructor is also prepared for a 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.