Jonas Maebe wrote:
On 10 Aug 2010, at 10:59, Frank Heckenbach wrote:
- All classes have a common ancestor.
Most classes have a common ancestor, but not all of them do. There are at least two root classes in the Cocoa framework: NSObject (the most commonly used one) and NSProxy (mostly used for language bridges and for remote message passing).
You can define as many root classes as you want, with the only restriction that they have to conform to the NSObject protocol (a protocol is similar to an interface in Java/Delphi-style Pascal -- and yes, protocols and classes can have the same name).
Then I probably got confused by that. But still trying to understand the differences coming from C++ one could say, protocols (like Java/Delphi interfaces) correspond to abstract classes with only abstact virtual methods, implementing interfaces corresponds to (multiple) inheritance, so the NSObject protocol would be the common ancestor, all classes implement (inherit from) it, and "id" would then be a pointer/reference to "NSObject_protocol".
(That's not a new thing, we've had this discussion WRT Pascal object models.) Many Objective-C proponents seem to tout this as a big advantage, I see it as a restriction. E.g., that an "untyped" object pointer exists and is still useful (in contrast to a real untyped pointer).
There is an "untyped object pointer" in Objective-C, but it's unrelated to any root class. This type is called "id", and it is actually more like universally typed: without type casting, you can a) assign an id-typed variable to any variable of another class type (or of the id type),
And if the object that the id-variable references is not of the other class type? Do you get a runtime exception, or does the assignment still work? The latter would seem wrong to me, the former corresponds to C++ dynamic_cast.
Frank