Reputation: 38213
Setup:
@interface Base : NSObject {}
@end
@interface Subclass : Base {}
@end
…
Subclass* sub = …;
Is there a difference between:
// No explicit cast.
Base* base = sub;
and:
// Explicit cast, but does this actually DO anything different at runtime?
Base* base = (Base*) sub;
Upvotes: 2
Views: 159
Reputation: 104065
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.
Upvotes: 3
Reputation: 3310
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.
Upvotes: -1
Reputation: 13146
Hmmh Warning: incompatible Objective-C types initializing 'struct AbstractClass *', expected 'struct ConcreteClass *'
Upvotes: 0
Reputation: 4428
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.
Upvotes: 0