Why do Objective-c objects have to be dynamically allocated? Why do I have to make it a pointer to an object, unlike in C++ I can create them on stack? Thanks.
the primary reason: not knowing how much stack size to reserve.
existing conventions and uses also make lifting the restriction quite difficult.
dynamic messaging does not matter in this case, as setting the right 'vtable' at initialization is trivial.
in c++, the size of a stack object is always known (and if it's wrong, you know what to expect). an objc alloc/init sequence can return any one of several types -- each with different sizes (it's essentially a factory), or nothing at all.
the size can also vary at runtime (e.g. you can add fields to a class via the runtime).
Update 1
i was curious about this, so i made a little test program as a proof of concept.
i was able to implement a simple stack based objc class hierarchy, which also implemented a good chunk of NSObject
's interface -- of course, omitting the reference counting and dynamic allocation interfaces as it did not relate to the proof of concept. at any rate, my simple class hierarchy was not fully compatible with the NSObject class or protocol, so it isn't something that should be used where NSObject types are expected, for obvious reasons. therefore, it is possible (and not particularly difficult) to accomplish this, if you really wanted stack based objc objects.
you don't have to do anything different from c++ to reserve the stack space. the stack size to reserve is still a restriction in some areas (consider factory methods, class clusters, etc.).
there are also a few runtime functionalities which will not work by default. the best example here is the ability to add ivars at runtime. you could in fact accomodate this functionality, if you needed it. i didn't bother with that exercise.
naturally, the base interface could take several deviations - one deviation that i made for fun was adding the ability to exchange the implementations (type) of a living object.
have fun
Update 2
as it turns out, GCC accepts the proof of concept i wrote. unfortunately, this has been banned in clang due to problems/dangers which can be encountered in reserving the correct size (considering the dynamic features of the language...). example: clang forbids sizeof(NSObject)
. oh well.