objective-cobjectstack

Objective C allocating objects on the stack


I am new to Objective C and doing some practice with objects. While something like Fraction* f = [[Fraction alloc] init ]; works, whenever I try to do Fraction c; I get Interface type cannot be statically allocated Is there anyway to allocate objects on the stack (like in c++) ? or am I trying the wrong thing ?


Solution

  • You cannot allocate an object statically in Objective C. There are a lot of reasons for this. Including the fact that objects should be initialized but initialization methods are allowed to change the address of the object.

    In C++ a constructor must initialize the object it's called upon and cannot, in any way, change the object address. This is not true in Objective C. The equivalent of constructors (the alloc+init* sequence or a class level method) are allowed to decide that they are going to change the address of the object they are called upon (they will take care of freeing the original object, of course).

    There's no way for them to free the statically allocated memory nor to change the address of your stack, of course.