Tutorial :Destructor in Objective-C++



Question:

I have an objective-C++ class which contain some honest C++ object pointers.

When the Obj-C++ class is destroyed does it call dealloc immediately? If so, then is the best way to destroy the C++ class by putting

delete obj  

in the dealloc method?


Solution:1

I presume when you say "Obj-C++ class" you mean an Objective-C class that happens to contain some C++ classes.

Objective-C classes don't call dealloc when they're destroyed; they're destroyed by having the dealloc message sent to them.

With that bit of pedantry out the way, if your init method instantiates obj then, yes, call delete obj in the dealloc:

-(void)dealloc {    delete obj;    [super dealloc];  }  


Solution:2

As a supplement to Frank Shearar's correct answer, provided you are using the OSX 10.4 or later SDK (and you probably are; though I'm not sure about the iPhone runtime here) you can also include C++ members of Objective-C classes, i.e. without resorting to a pointer. The problem in earlier versions of the OSX SDK was that the constructor and destructor of the C++ member simply would not get called. However, by specifying the fobjc-call-cxx-cdtors compiler option (in XCode it is exposed as the setting GCC_OBJC_CALL_CXX_CDTORS), the ctor and dtor will get called. See also Apple docs, a bit down that page.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »