pretty important tip about destructors

One thing I came across while working on the InteractiveObject and ObjCPointer classes - if a class does not have a virtual destructor, and you extend it, and try to delete it through a pointer to a base class… the extended class does not get deleted correctly. Its destructor does not get called, and depending on the inheritance tree the correct section and amount of memory isn’t even cleared and you can get runtime errors when trying to delete because the pointer is not pointing to the beginning of the whole object but just the base object (on osx: malloc: *** error for object 0x86740c: Non-aligned pointer being freed). And this happens even if the base class has no destructor declared.

To make it slightly clearer:

  
  
class MyPoint : public ofPoint {  
   ....  
}  
  
void usePoint(ofPoint *point) {  
   ....  
   delete point;  
}  
  
usePoint(new MyPoint);  
  

The above code should work, and is the whole principle of OOP. But the last line will not delete a MyPoint, it will delete an ofPoint. MyPoint’s destructor will not get called causing a memory leak if you were doing any cleaning in its destructor. For this to work, ofPoint would need a virtual destructor. Even though ofPoint doesn’t have a destructor at the moment, it needs an empty virtual destructor.

  
  
class Sprite : public ofPoint, public ofTexture {  
   ...  
}  
  
void useTexture(ofTexture *texture) {  
   ...    
   delete texture;  
}  
  
useTexture(new Sprite);  
  

Multiple inheritance is always a bit tricky and not always the best design pattern, but the above code should work based on OOP principles. But in this case it will not delete the right amount of memory, and in fact give a (non-lethal) runtime error with non-aligned pointer being freed. Again ofPoint and ofTexture need virtual destructors. In fact it seems that any class that has the possibility of being extended should always have a virtual destructor (even if its empty).

Just thought I’d share my late night reading with you all :stuck_out_tongue: and hopefully we can have virtual destructors for the next release?

Hey memo,

thanks a lot for the insight. I was pretty puzzled about virtual destructors and always thought they had something to do with copy-constructors… Well explained, thanks!

good catch!