开发者

Objective C: Is there a difference between these two statements?

Setup:

@interface Base : NSObject {}
@end

@interface Subclass : Base {}
@end

…

Subclass* sub = …;

Is there a difference between:

// No e开发者_运维百科xplicit cast.
Base* base = sub;

and:

// Explicit cast, but does this actually DO anything different at runtime?
Base* base = (Base*) sub;


Treating a subclass like its parent class is quite common and safe. (Unless you’re misusing inheritance in your design.) The cast does nothing extra in runtime and is not needed during compilation; it’s completely useless as far as the machine is concerned.


You will get a compiler warning about ClassSuper* super = base; since not every ClassBase instance is ClassSuper instance. So if you really know what you do you should make explicit cast to stop compiler from whining.


Hmmh Warning: incompatible Objective-C types initializing 'struct AbstractClass *', expected 'struct ConcreteClass *'


Your casted statement is only valid if base really points to an instance of ClassSuper. Since ClassBase includes more types then ClassSuper your cast might fail during runtime!

Your first statement though won't fail because Objective-C doesn't really care about the type during assignment. So your ClassSuper* super is more an id super during runtime. The cast though will be verified and throw errors if not fulfilled.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜